Bounded Pool Executor

0.0.3 · active · verified Tue Apr 14

Bounded Pool Executor is a Python library that provides `BoundedThreadPoolExecutor` and `BoundedProcessPoolExecutor` classes, extending `concurrent.futures` to manage a fixed-size queue for tasks. This prevents memory exhaustion that can occur with the standard unbounded queues in `concurrent.futures` when submitting a large number of tasks. The current version is 0.0.3, offering a solution to prevent memory leaks in high-concurrency scenarios by blocking `submit` calls when the queue is full.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `BoundedThreadPoolExecutor` to execute tasks while limiting the number of concurrent tasks and the size of the waiting queue. The `submit` method will block if the queue, including currently executing tasks, reaches its `max_queue_size`.

import time
from bounded_pool_executor import BoundedThreadPoolExecutor

def my_task(n):
    time.sleep(0.1) # Simulate some work
    return f"Task {n} completed"

max_workers = 2
max_queue_size = 4 # total slots = max_workers + max_queue_size_for_waiting_tasks

print(f"Using BoundedThreadPoolExecutor with {max_workers} workers and queue size {max_queue_size}")

futures = []
with BoundedThreadPoolExecutor(max_workers=max_workers, max_queue_size=max_queue_size) as pool:
    for i in range(1, 10):
        print(f"Submitting task {i}...")
        # The submit call will block if the queue is full
        future = pool.submit(my_task, i)
        futures.append(future)

print("All tasks submitted. Waiting for results...")
for future in futures:
    print(future.result())

view raw JSON →