Skip to content

executor

Thread pool executor with dynamic worker scaling and async result support.

This module provides: - Executor: Thread pool with configurable min/max workers and idle timeout - Queue: Thread-safe task queue with start/stop control - Task: Callable wrapper that captures exceptions - AsyncResult: Future-like object for retrieving task results - common_executor(): Global singleton executor instance

Example
import py_misc_utils.executor as xe

ex = xe.Executor(max_threads=4, min_threads=1, name_prefix='Demo')
res = ex.submit_result(lambda a, b: a + b, 2, 3)
assert res.wait() == 5
ex.submit(print, 'fire and forget')
ex.wait_for_idle()
ex.shutdown()

Task

Callable task wrapper that executes a function and optionally sets a result.

Captures exceptions and wraps them in _ExceptionWrapper for later re-raising.

Source code in py_misc_utils/executor.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Task:
  """Callable task wrapper that executes a function and optionally sets a result.

  Captures exceptions and wraps them in _ExceptionWrapper for later re-raising.
  """

  def __init__(self, fn, args=None, kwargs=None, aresult=None):
    """Initialize a task.

    Args:
      fn: Callable to execute.
      args: Positional arguments (default: empty tuple).
      kwargs: Keyword arguments (default: empty dict).
      aresult: Optional AsyncResult to set with the result.
    """
    self._fn = fn
    self._args = args or ()
    self._kwargs = kwargs or dict()
    self._aresult = aresult

  def __call__(self):
    """Execute the task function and set result if provided."""
    try:
      fnres = self._fn(*self._args, **self._kwargs)
    except Exception as ex:  # noqa: BLE001 -- task boundary: any user-callable failure is delivered to the waiter as _ExceptionWrapper
      alog.exception(ex, exmsg='Exception while running task')
      fnres = _ExceptionWrapper(exception=ex)

    if self._aresult is not None:
      self._aresult.set(fnres)

AsyncResult

Future-like object for retrieving asynchronous task results.

Thread-safe with blocking wait() and optional timeout. If the task raised an exception, wait() re-raises it instead of returning a value.

Example
import py_misc_utils.executor as xe

res = xe.common_executor().submit_result(len, 'abc')
assert res.wait() == 3
# The same instance is returned on every call.
assert xe.common_executor() is xe.common_executor()
Source code in py_misc_utils/executor.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
class AsyncResult:
  """Future-like object for retrieving asynchronous task results.

  Thread-safe with blocking wait() and optional timeout. If the task
  raised an exception, wait() re-raises it instead of returning a value.

  Example:
    import py_misc_utils.executor as xe

    res = xe.common_executor().submit_result(len, 'abc')
    assert res.wait() == 3
    # The same instance is returned on every call.
    assert xe.common_executor() is xe.common_executor()
  """

  def __init__(self):
    """Initialize an unset result."""
    self._cond = threading.Condition(lock=threading.Lock())
    self._result = VOID

  def set(self, result):
    """Set the result and notify waiters.

    Args:
      result: Result value or _ExceptionWrapper.
    """
    with self._cond:
      self._result = result
      self._cond.notify_all()

  def wait(self, timeout=None):
    """Wait for and retrieve the result.

    Args:
      timeout: Maximum time to wait in seconds (default: None, wait forever).

    Returns:
      The result value.

    Raises:
      Exception: If the task raised an exception.
      TimeoutError: If timeout expires before result is set.
    """
    with self._cond:
      # No need for a loop here, as the condition is signaled only when result
      # is set by the producer.
      if self._result is VOID:
        self._cond.wait(timeout=timeout)

      if isinstance(self._result, _ExceptionWrapper):
        raise self._result.exception

      return self._result

set(result)

Set the result and notify waiters.

Parameters:

Name Type Description Default
result

Result value or _ExceptionWrapper.

required
Source code in py_misc_utils/executor.py
 92
 93
 94
 95
 96
 97
 98
 99
100
def set(self, result):
  """Set the result and notify waiters.

  Args:
    result: Result value or _ExceptionWrapper.
  """
  with self._cond:
    self._result = result
    self._cond.notify_all()

wait(timeout=None)

Wait for and retrieve the result.

Parameters:

Name Type Description Default
timeout

Maximum time to wait in seconds (default: None, wait forever).

None

Returns:

Type Description

The result value.

Raises:

Type Description
Exception

If the task raised an exception.

TimeoutError

If timeout expires before result is set.

Source code in py_misc_utils/executor.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def wait(self, timeout=None):
  """Wait for and retrieve the result.

  Args:
    timeout: Maximum time to wait in seconds (default: None, wait forever).

  Returns:
    The result value.

  Raises:
    Exception: If the task raised an exception.
    TimeoutError: If timeout expires before result is set.
  """
  with self._cond:
    # No need for a loop here, as the condition is signaled only when result
    # is set by the producer.
    if self._result is VOID:
      self._cond.wait(timeout=timeout)

    if isinstance(self._result, _ExceptionWrapper):
      raise self._result.exception

    return self._result

Queue

Thread-safe task queue with start/stop control.

Supports blocking get with timeout and graceful shutdown. stop() just increments a counter, so it can be called multiple times, and pending items are still returned by get() - only once the queue is empty (and stopped) get() stops blocking and returns None.

Example
import py_misc_utils.executor as xe

q = xe.Queue()
q.put('a')
q.put('b')
assert q.get(timeout=1.0) == 'a'
q.stop()
# Pending items are still returned after stop - None means exhausted.
assert q.get() == 'b'
assert q.get(timeout=0.1) is None
Source code in py_misc_utils/executor.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class Queue:
  """Thread-safe task queue with start/stop control.

  Supports blocking get with timeout and graceful shutdown. stop() just
  increments a counter, so it can be called multiple times, and pending
  items are still returned by get() - only once the queue is empty (and
  stopped) get() stops blocking and returns None.

  Example:
    import py_misc_utils.executor as xe

    q = xe.Queue()
    q.put('a')
    q.put('b')
    assert q.get(timeout=1.0) == 'a'
    q.stop()
    # Pending items are still returned after stop - None means exhausted.
    assert q.get() == 'b'
    assert q.get(timeout=0.1) is None
  """

  def __init__(self):
    """Initialize an empty queue."""
    self._lock = threading.Lock()
    self._cond = threading.Condition(lock=self._lock)
    self._queue = collections.deque()
    self._stopped = 0

  def put(self, task):
    """Add a task to the queue.

    Args:
      task: Task to enqueue.

    Returns:
      New queue length.
    """
    with self._lock:
      self._queue.append(task)
      self._cond.notify()

      return len(self._queue)

  def get(self, timeout=None):
    """Get a task from the queue, blocking until available or timeout.

    Even if the queue is stopped, pending items are still returned. Once
    the queue is both stopped and empty, None is returned - so None is
    the "no more work" sentinel used by the worker loop.

    Args:
      timeout: Maximum time to wait in seconds (default: None, wait forever).

    Returns:
      Task from the queue, or None if stopped and empty.
    """
    with self._lock:
      while True:
        # Even in case of stopped queue, always return pending items if available.
        if self._queue:
          return self._queue.popleft()
        if self._stopped > 0 or not self._cond.wait(timeout=timeout):
          break

  def start(self):
    """Resume the queue (decrement stop counter)."""
    with self._lock:
      self._stopped -= 1

  def stop(self):
    """Stop the queue (increment stop counter) and wake all waiters."""
    with self._lock:
      self._stopped += 1
      self._cond.notify_all()

  def __len__(self):
    """Return the number of pending tasks."""
    with self._lock:
      return len(self._queue)

put(task)

Add a task to the queue.

Parameters:

Name Type Description Default
task

Task to enqueue.

required

Returns:

Type Description

New queue length.

Source code in py_misc_utils/executor.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def put(self, task):
  """Add a task to the queue.

  Args:
    task: Task to enqueue.

  Returns:
    New queue length.
  """
  with self._lock:
    self._queue.append(task)
    self._cond.notify()

    return len(self._queue)

get(timeout=None)

Get a task from the queue, blocking until available or timeout.

Even if the queue is stopped, pending items are still returned. Once the queue is both stopped and empty, None is returned - so None is the "no more work" sentinel used by the worker loop.

Parameters:

Name Type Description Default
timeout

Maximum time to wait in seconds (default: None, wait forever).

None

Returns:

Type Description

Task from the queue, or None if stopped and empty.

Source code in py_misc_utils/executor.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def get(self, timeout=None):
  """Get a task from the queue, blocking until available or timeout.

  Even if the queue is stopped, pending items are still returned. Once
  the queue is both stopped and empty, None is returned - so None is
  the "no more work" sentinel used by the worker loop.

  Args:
    timeout: Maximum time to wait in seconds (default: None, wait forever).

  Returns:
    Task from the queue, or None if stopped and empty.
  """
  with self._lock:
    while True:
      # Even in case of stopped queue, always return pending items if available.
      if self._queue:
        return self._queue.popleft()
      if self._stopped > 0 or not self._cond.wait(timeout=timeout):
        break

start()

Resume the queue (decrement stop counter).

Source code in py_misc_utils/executor.py
191
192
193
194
def start(self):
  """Resume the queue (decrement stop counter)."""
  with self._lock:
    self._stopped -= 1

stop()

Stop the queue (increment stop counter) and wake all waiters.

Source code in py_misc_utils/executor.py
196
197
198
199
200
def stop(self):
  """Stop the queue (increment stop counter) and wake all waiters."""
  with self._lock:
    self._stopped += 1
    self._cond.notify_all()

Executor

Thread pool executor with dynamic worker scaling.

Maintains a minimum number of persistent workers and scales up to a maximum based on queue depth. Workers beyond the minimum have an idle timeout.

Example
import py_misc_utils.executor as xe

ex = xe.Executor(max_threads=4, min_threads=1, name_prefix='Demo')
res = ex.submit_result(lambda a, b: a + b, 2, 3)
assert res.wait() == 5
ex.submit(print, 'fire and forget')
ex.wait_for_idle()
ex.shutdown()
Source code in py_misc_utils/executor.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
class Executor:
  """Thread pool executor with dynamic worker scaling.

  Maintains a minimum number of persistent workers and scales up to a maximum
  based on queue depth. Workers beyond the minimum have an idle timeout.

  Example:
    import py_misc_utils.executor as xe

    ex = xe.Executor(max_threads=4, min_threads=1, name_prefix='Demo')
    res = ex.submit_result(lambda a, b: a + b, 2, 3)
    assert res.wait() == 5
    ex.submit(print, 'fire and forget')
    ex.wait_for_idle()
    ex.shutdown()
  """

  def __init__(self,
               max_threads=None,
               min_threads=None,
               name_prefix=None,
               idle_timeout=None):
    """Initialize the executor.

    Args:
      max_threads: Maximum number of worker threads (default: auto).
      min_threads: Minimum number of persistent workers (default: auto).
      name_prefix: Prefix for worker thread names (default: 'Executor').
      idle_timeout: Seconds before idle workers exit (default: from
        EXECUTOR_IDLE_TIMEOUT env var or 5).
    """
    self._min_threads, self._max_threads = _compute_num_threads(
        min_threads, max_threads)
    self._name_prefix = name_prefix or 'Executor'
    self._idle_timeout = idle_timeout or ut.getenv(
        'EXECUTOR_IDLE_TIMEOUT', dtype=int, defval=5)
    self._lock = threading.Lock()
    self._queue = Queue()
    self._workers = dict()
    self._thread_counter = 0
    self._idle_cond = threading.Condition(lock=self._lock)

  def _unregister_worker(self, worker):
    """Called by worker when it exits."""
    alog.spam(f'Unregistering worker thread {worker.ident}')
    with self._lock:
      self._workers.pop(worker.ident, None)
      if not self._workers:
        self._idle_cond.notify_all()

  def _new_name(self):
    """Generate a new worker thread name."""
    self._thread_counter += 1

    return f'{self._name_prefix}-{self._thread_counter}'

  def _maybe_add_worker(self, queued):
    """Add a worker if queue depth warrants it or below minimum."""
    num_threads = len(self._workers)
    if ((queued > 1 and num_threads < self._max_threads) or
        num_threads < self._min_threads):
      # Up to min_threads the workers should never quit, so they get None as
      # timeout, while the one after that will get _idle_timeout which will
      # make them quit if no task is fetched within such timeout.
      idle_timeout = self._idle_timeout if num_threads > self._min_threads else None

      worker = _Worker(weakref.ref(self),
                       self._queue,
                       self._new_name(),
                       idle_timeout=idle_timeout)

      self._workers[worker.ident] = worker

      alog.spam(f'New thread #{num_threads} with ID {worker.ident}')

  def _submit_task(self, task):
    """Submit a task and potentially scale up workers.

    Args:
      task: Task to submit.
    """
    with self._lock:
      queued = self._queue.put(task)
      self._maybe_add_worker(queued)

  def submit(self, fn, *args, **kwargs):
    """Submit a fire-and-forget task.

    Args:
      fn: Callable to execute.
      *args: Positional arguments.
      **kwargs: Keyword arguments.
    """
    self._submit_task(Task(fn, args=args, kwargs=kwargs))

  def submit_result(self, fn, *args, **kwargs):
    """Submit a task and return an AsyncResult for retrieving the result.

    Args:
      fn: Callable to execute.
      *args: Positional arguments.
      **kwargs: Keyword arguments.

    Returns:
      AsyncResult that can be waited on for the result.
    """
    aresult = AsyncResult()

    self._submit_task(Task(fn, args=args, kwargs=kwargs, aresult=aresult))

    return aresult

  def shutdown(self):
    """Stop the executor and wait for all workers to exit."""
    alog.debug0('Stopping executor')
    self._queue.stop()
    with self._lock:
      alog.debug0('Waiting executor workers exit')
      while self._workers:
        self._idle_cond.wait()

  def wait_for_idle(self, timeout=None, timegen=None, waiter=None):
    """Wait for all tasks to complete and workers to become idle.

    Temporarily stops the queue to prevent new tasks from being added -
    tasks submitted concurrently are queued but do not spawn extra workers
    during the wait (the queue is restarted before returning).

    Args:
      timeout: Maximum time to wait in seconds (default: None).
      timegen: Optional time generator for CondWaiter.
      waiter: Optional CondWaiter instance.

    Returns:
      True if all workers became idle, False if timeout expired.
    """
    alog.debug0('Waiting for idle ...')

    waiter = waiter or cwait.CondWaiter(timeout=timeout, timegen=timegen)
    self._queue.stop()
    try:
      with self._lock:
        while self._workers:
          if not waiter.wait(self._idle_cond):
            return False
    finally:
      self._queue.start()
      alog.debug0('Waiting for idle ... done')

    return True

submit(fn, *args, **kwargs)

Submit a fire-and-forget task.

Parameters:

Name Type Description Default
fn

Callable to execute.

required
*args

Positional arguments.

()
**kwargs

Keyword arguments.

{}
Source code in py_misc_utils/executor.py
358
359
360
361
362
363
364
365
366
def submit(self, fn, *args, **kwargs):
  """Submit a fire-and-forget task.

  Args:
    fn: Callable to execute.
    *args: Positional arguments.
    **kwargs: Keyword arguments.
  """
  self._submit_task(Task(fn, args=args, kwargs=kwargs))

submit_result(fn, *args, **kwargs)

Submit a task and return an AsyncResult for retrieving the result.

Parameters:

Name Type Description Default
fn

Callable to execute.

required
*args

Positional arguments.

()
**kwargs

Keyword arguments.

{}

Returns:

Type Description

AsyncResult that can be waited on for the result.

Source code in py_misc_utils/executor.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def submit_result(self, fn, *args, **kwargs):
  """Submit a task and return an AsyncResult for retrieving the result.

  Args:
    fn: Callable to execute.
    *args: Positional arguments.
    **kwargs: Keyword arguments.

  Returns:
    AsyncResult that can be waited on for the result.
  """
  aresult = AsyncResult()

  self._submit_task(Task(fn, args=args, kwargs=kwargs, aresult=aresult))

  return aresult

shutdown()

Stop the executor and wait for all workers to exit.

Source code in py_misc_utils/executor.py
385
386
387
388
389
390
391
392
def shutdown(self):
  """Stop the executor and wait for all workers to exit."""
  alog.debug0('Stopping executor')
  self._queue.stop()
  with self._lock:
    alog.debug0('Waiting executor workers exit')
    while self._workers:
      self._idle_cond.wait()

wait_for_idle(timeout=None, timegen=None, waiter=None)

Wait for all tasks to complete and workers to become idle.

Temporarily stops the queue to prevent new tasks from being added - tasks submitted concurrently are queued but do not spawn extra workers during the wait (the queue is restarted before returning).

Parameters:

Name Type Description Default
timeout

Maximum time to wait in seconds (default: None).

None
timegen

Optional time generator for CondWaiter.

None
waiter

Optional CondWaiter instance.

None

Returns:

Type Description

True if all workers became idle, False if timeout expired.

Source code in py_misc_utils/executor.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def wait_for_idle(self, timeout=None, timegen=None, waiter=None):
  """Wait for all tasks to complete and workers to become idle.

  Temporarily stops the queue to prevent new tasks from being added -
  tasks submitted concurrently are queued but do not spawn extra workers
  during the wait (the queue is restarted before returning).

  Args:
    timeout: Maximum time to wait in seconds (default: None).
    timegen: Optional time generator for CondWaiter.
    waiter: Optional CondWaiter instance.

  Returns:
    True if all workers became idle, False if timeout expired.
  """
  alog.debug0('Waiting for idle ...')

  waiter = waiter or cwait.CondWaiter(timeout=timeout, timegen=timegen)
  self._queue.stop()
  try:
    with self._lock:
      while self._workers:
        if not waiter.wait(self._idle_cond):
          return False
  finally:
    self._queue.start()
    alog.debug0('Waiting for idle ... done')

  return True

common_executor()

Get the global singleton executor instance.

Creates the executor on first call with configuration from environment: - EXECUTOR_WORKERS: max threads - EXECUTOR_NAME: name prefix

Returns:

Type Description

The global Executor instance.

Example
import py_misc_utils.executor as xe

res = xe.common_executor().submit_result(len, 'abc')
assert res.wait() == 3
Source code in py_misc_utils/executor.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def common_executor():
  """Get the global singleton executor instance.

  Creates the executor on first call with configuration from environment:
  - EXECUTOR_WORKERS: max threads
  - EXECUTOR_NAME: name prefix

  Returns:
    The global Executor instance.

  Example:
    import py_misc_utils.executor as xe

    res = xe.common_executor().submit_result(len, 'abc')
    assert res.wait() == 3
  """
  global _EXECUTOR

  with _LOCK:
    if _EXECUTOR is None:
      _EXECUTOR = Executor(
          max_threads=ut.getenv('EXECUTOR_WORKERS', dtype=int),
          name_prefix=os.getenv('EXECUTOR_NAME', 'CommonExecutor'),
      )

    return _EXECUTOR