Skip to content

async_manager

Async task management with multiprocessing workers and asyncio event loops.

This module provides: - AsyncContext: Manages multiple async context managers - AsyncManager: Pool of worker processes running asyncio event loops - AsyncRunner: Single-threaded asyncio event loop in a background thread - run_async(): Convenience function to submit coroutines to the global runner

Example
import concurrent.futures
import py_misc_utils.async_manager as am

async def add(a, b):
  return a + b

fut = am.run_async(add(2, 3))
assert isinstance(fut, concurrent.futures.Future)
assert fut.result(timeout=5.0) == 5

AsyncContext

Manages multiple async context managers with shared lifecycle.

Allows adding, removing, and getting context managers by name. Automatically enters/exits all contexts on close. get() enters a context only the first time it is requested - later calls with the same name return the same aenter() result.

Source code in py_misc_utils/async_manager.py
 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
 63
 64
 65
 66
 67
 68
 69
 70
 71
 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
class AsyncContext:
  """Manages multiple async context managers with shared lifecycle.

  Allows adding, removing, and getting context managers by name.
  Automatically enters/exits all contexts on close. get() enters a context
  only the first time it is requested - later calls with the same name
  return the same __aenter__() result.
  """

  def __init__(self):
    """Initialize an empty context manager collection."""
    self._contexts = dict()

  async def add(self, name, context):
    """Add and enter a context manager.

    Args:
      name: Unique name for the context.
      context: Async context manager instance.

    Returns:
      Result of context.__aenter__().
    """
    result = await context.__aenter__()
    self._contexts[name] = (context, result)

    return result

  async def remove(self, name):
    """Remove and exit a context manager by name.

    Args:
      name: Name of the context to remove.
    """
    context, _ = self._contexts.pop(name)
    await context.__aexit__(None, None, None)

  async def get(self, name, context_ctor):
    """Get or create a context manager by name.

    Args:
      name: Name of the context.
      context_ctor: Callable returning a new async context manager instance.

    Returns:
      Result of context.__aenter__() for the context.
    """
    context_result = self._contexts.get(name)
    if context_result is None:
      result = await self.add(name, context_ctor())
    else:
      result = context_result[1]

    return result

  async def close(self, *exc):
    """Exit all managed contexts.

    Args:
      *exc: Exception info to pass to __aexit__ (type, value, traceback).

    Raises:
      Exception: If any context's __aexit__ returns False and an exception
        was being handled.
    """
    rexc = exc or (None, None, None)
    needs_raise = False
    for context, _ in self._contexts.values():
      exitres = await context.__aexit__(*rexc)
      needs_raise = needs_raise or not exitres

    self._contexts = dict()
    if needs_raise and rexc[1] is not None:
      raise rexc[1]

  async def __aenter__(self):
    """Enter the async context (returns self)."""
    return self

  async def __aexit__(self, *exc):
    """Exit all managed contexts."""
    await self.close(*exc)

    return False

add(name, context) async

Add and enter a context manager.

Parameters:

Name Type Description Default
name

Unique name for the context.

required
context

Async context manager instance.

required

Returns:

Type Description

Result of context.aenter().

Source code in py_misc_utils/async_manager.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
async def add(self, name, context):
  """Add and enter a context manager.

  Args:
    name: Unique name for the context.
    context: Async context manager instance.

  Returns:
    Result of context.__aenter__().
  """
  result = await context.__aenter__()
  self._contexts[name] = (context, result)

  return result

remove(name) async

Remove and exit a context manager by name.

Parameters:

Name Type Description Default
name

Name of the context to remove.

required
Source code in py_misc_utils/async_manager.py
64
65
66
67
68
69
70
71
async def remove(self, name):
  """Remove and exit a context manager by name.

  Args:
    name: Name of the context to remove.
  """
  context, _ = self._contexts.pop(name)
  await context.__aexit__(None, None, None)

get(name, context_ctor) async

Get or create a context manager by name.

Parameters:

Name Type Description Default
name

Name of the context.

required
context_ctor

Callable returning a new async context manager instance.

required

Returns:

Type Description

Result of context.aenter() for the context.

Source code in py_misc_utils/async_manager.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
async def get(self, name, context_ctor):
  """Get or create a context manager by name.

  Args:
    name: Name of the context.
    context_ctor: Callable returning a new async context manager instance.

  Returns:
    Result of context.__aenter__() for the context.
  """
  context_result = self._contexts.get(name)
  if context_result is None:
    result = await self.add(name, context_ctor())
  else:
    result = context_result[1]

  return result

close(*exc) async

Exit all managed contexts.

Parameters:

Name Type Description Default
*exc

Exception info to pass to aexit (type, value, traceback).

()

Raises:

Type Description
Exception

If any context's aexit returns False and an exception was being handled.

Source code in py_misc_utils/async_manager.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
async def close(self, *exc):
  """Exit all managed contexts.

  Args:
    *exc: Exception info to pass to __aexit__ (type, value, traceback).

  Raises:
    Exception: If any context's __aexit__ returns False and an exception
      was being handled.
  """
  rexc = exc or (None, None, None)
  needs_raise = False
  for context, _ in self._contexts.values():
    exitres = await context.__aexit__(*rexc)
    needs_raise = needs_raise or not exitres

  self._contexts = dict()
  if needs_raise and rexc[1] is not None:
    raise rexc[1]

AsyncManager

Pool of worker processes for parallel async task execution.

Distributes work across workers using a simple least-loaded strategy. Each worker runs an independent asyncio event loop in its own process. Each worker shares one AsyncContext, so context managers created via context.get(name, ctor) live as long as the worker - not per work item.

NOTE: work ctors must be picklable (module-level callables) since they travel through a multiprocessing queue to the worker processes.

Example
class Ctx:
  async def __aenter__(self):
    return 'ctx-value'

  async def __aexit__(self, *exc):
    return False

def make_ctx():
  return Ctx()

async def work(context):
  ctx = await context.get('res', make_ctx)
  return (ctx, 21 * 2)

m = am.AsyncManager(num_workers=2)
m.enqueue_work('w1', work)
wid, res = m.fetch_result(block=True, timeout=5.0)
assert wid == 'w1' and res == ('ctx-value', 42)
m.close()
Source code in py_misc_utils/async_manager.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
class AsyncManager:
  """Pool of worker processes for parallel async task execution.

  Distributes work across workers using a simple least-loaded strategy.
  Each worker runs an independent asyncio event loop in its own process.
  Each worker shares one AsyncContext, so context managers created via
  context.get(name, ctor) live as long as the worker - not per work item.

  NOTE: work ctors must be picklable (module-level callables) since they
  travel through a multiprocessing queue to the worker processes.

  Example:
    class Ctx:
      async def __aenter__(self):
        return 'ctx-value'

      async def __aexit__(self, *exc):
        return False

    def make_ctx():
      return Ctx()

    async def work(context):
      ctx = await context.get('res', make_ctx)
      return (ctx, 21 * 2)

    m = am.AsyncManager(num_workers=2)
    m.enqueue_work('w1', work)
    wid, res = m.fetch_result(block=True, timeout=5.0)
    assert wid == 'w1' and res == ('ctx-value', 42)
    m.close()
  """

  def __init__(self, num_workers=None, mpctx=multiprocessing):
    """Initialize the async manager with a worker pool.

    Args:
      num_workers: Number of worker processes (default: CPU count).
      mpctx: Multiprocessing context (default: multiprocessing).
    """
    num_workers = num_workers or os.cpu_count()

    self._out_queue = mpctx.Queue()
    self._workers = [_Worker(mpctx, i, self._out_queue) for i in range(num_workers)]
    self._lock = threading.Lock()
    self._queued = np.zeros(num_workers, dtype=np.int64)

  def close(self):
    """Stop all worker processes."""
    for worker in self._workers:
      worker.stop()

  def enqueue_work(self, work_id, work_ctor):
    """Submit work to the least-loaded worker.

    Args:
      work_id: Unique identifier for the work item.
      work_ctor: Callable accepting 'context' kwarg, returning awaitable.
    """
    with self._lock:
      wid = np.argmin(self._queued)
      self._queued[wid] += 1
      worker = self._workers[wid]

    worker.enqueue_work(work_id, work_ctor)

  def fetch_result(self, block=True, timeout=None):
    """Fetch a completed work result.

    Results of failed work items carry a WorkException instance - raised
    work errors do not terminate the fetch loop.

    Args:
      block: Whether to block until a result is available (default: True).
      timeout: Maximum time to wait in seconds (default: None).

    Returns:
      Tuple of (work_id, result) or None if timeout and non-blocking.

    Raises:
      queue.Empty: If block=False and no result available.
    """
    try:
      wid, work_id, result = self._out_queue.get(block=block, timeout=timeout)

      with self._lock:
        self._queued[wid] -= 1

      return work_id, result
    except queue.Empty:
      pass

  def __enter__(self):
    """Context manager entry."""
    return self

  def __exit__(self, *exc):
    """Context manager exit: stop all workers."""
    self.close()

    return False

close()

Stop all worker processes.

Source code in py_misc_utils/async_manager.py
258
259
260
261
def close(self):
  """Stop all worker processes."""
  for worker in self._workers:
    worker.stop()

enqueue_work(work_id, work_ctor)

Submit work to the least-loaded worker.

Parameters:

Name Type Description Default
work_id

Unique identifier for the work item.

required
work_ctor

Callable accepting 'context' kwarg, returning awaitable.

required
Source code in py_misc_utils/async_manager.py
263
264
265
266
267
268
269
270
271
272
273
274
275
def enqueue_work(self, work_id, work_ctor):
  """Submit work to the least-loaded worker.

  Args:
    work_id: Unique identifier for the work item.
    work_ctor: Callable accepting 'context' kwarg, returning awaitable.
  """
  with self._lock:
    wid = np.argmin(self._queued)
    self._queued[wid] += 1
    worker = self._workers[wid]

  worker.enqueue_work(work_id, work_ctor)

fetch_result(block=True, timeout=None)

Fetch a completed work result.

Results of failed work items carry a WorkException instance - raised work errors do not terminate the fetch loop.

Parameters:

Name Type Description Default
block

Whether to block until a result is available (default: True).

True
timeout

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

None

Returns:

Type Description

Tuple of (work_id, result) or None if timeout and non-blocking.

Raises:

Type Description
Empty

If block=False and no result available.

Source code in py_misc_utils/async_manager.py
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
def fetch_result(self, block=True, timeout=None):
  """Fetch a completed work result.

  Results of failed work items carry a WorkException instance - raised
  work errors do not terminate the fetch loop.

  Args:
    block: Whether to block until a result is available (default: True).
    timeout: Maximum time to wait in seconds (default: None).

  Returns:
    Tuple of (work_id, result) or None if timeout and non-blocking.

  Raises:
    queue.Empty: If block=False and no result available.
  """
  try:
    wid, work_id, result = self._out_queue.get(block=block, timeout=timeout)

    with self._lock:
      self._queued[wid] -= 1

    return work_id, result
  except queue.Empty:
    pass

AsyncRunner

Single-threaded asyncio event loop running in a background thread.

Provides a way to run async coroutines from synchronous code. Automatically registers for cleanup on process exit.

Example
import py_misc_utils.async_manager as am

runner = am.AsyncRunner()

async def sq(x):
  return x * x

futs = [runner.run(sq(i)) for i in range(4)]
assert [f.result(timeout=5.0) for f in futs] == [0, 1, 4, 9]
runner.stop()
Source code in py_misc_utils/async_manager.py
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
class AsyncRunner:
  """Single-threaded asyncio event loop running in a background thread.

  Provides a way to run async coroutines from synchronous code.
  Automatically registers for cleanup on process exit.

  Example:
    import py_misc_utils.async_manager as am

    runner = am.AsyncRunner()

    async def sq(x):
      return x * x

    futs = [runner.run(sq(i)) for i in range(4)]
    assert [f.result(timeout=5.0) for f in futs] == [0, 1, 4, 9]
    runner.stop()
  """

  def __init__(self):
    """Initialize and start the background thread with event loop."""
    self._loop = asyncio.new_event_loop()
    self._thread = threading.Thread(target=self._async_runner, daemon=True)
    self._thread.start()
    self._cid = cleanups.register(self.stop)

  def _async_runner(self):
    """Thread target: run the event loop forever."""
    asyncio.set_event_loop(self._loop)
    self._loop.run_forever()

  def stop(self):
    """Stop the event loop and join the thread."""
    self._loop.call_soon_threadsafe(self._loop.stop)
    self._thread.join()

  def run(self, coro):
    """Submit a coroutine to the event loop.

    Args:
      coro: Coroutine to execute.

    Returns:
      concurrent.futures.Future for the coroutine result.
    """
    return asyncio.run_coroutine_threadsafe(coro, self._loop)

stop()

Stop the event loop and join the thread.

Source code in py_misc_utils/async_manager.py
345
346
347
348
def stop(self):
  """Stop the event loop and join the thread."""
  self._loop.call_soon_threadsafe(self._loop.stop)
  self._thread.join()

run(coro)

Submit a coroutine to the event loop.

Parameters:

Name Type Description Default
coro

Coroutine to execute.

required

Returns:

Type Description

concurrent.futures.Future for the coroutine result.

Source code in py_misc_utils/async_manager.py
350
351
352
353
354
355
356
357
358
359
def run(self, coro):
  """Submit a coroutine to the event loop.

  Args:
    coro: Coroutine to execute.

  Returns:
    concurrent.futures.Future for the coroutine result.
  """
  return asyncio.run_coroutine_threadsafe(coro, self._loop)

run_async(coro)

Submit a coroutine to the global async runner.

Parameters:

Name Type Description Default
coro

Coroutine to execute.

required

Returns:

Type Description

concurrent.futures.Future for the coroutine result.

Source code in py_misc_utils/async_manager.py
372
373
374
375
376
377
378
379
380
381
def run_async(coro):
  """Submit a coroutine to the global async runner.

  Args:
    coro: Coroutine to execute.

  Returns:
    concurrent.futures.Future for the coroutine result.
  """
  return _async_runner().run(coro)