Skip to content

multiprocessing

Multiprocessing utilities for process creation with context propagation.

This module provides helpers for spawning child processes while preserving global namespace state, signal handling, and cleanup behavior. It includes the :class:TerminationError exception and functions such as :func:create_process and :func:procfn_wrap for robust process management.

Example
import py_misc_utils.multiprocessing as mpx

def worker(n):
  return n * n

proc = mpx.create_process(worker, (4,))
proc.start()
proc.join()

TerminationError

Bases: Exception

Raised when a process receives SIGTERM and should terminate.

The signal handler installed by procfn_wrap converts SIGTERM into this exception, so that the usual unwinding - cleanups included - happens before the process exits with code 1.

Source code in py_misc_utils/multiprocessing.py
30
31
32
33
34
35
36
class TerminationError(Exception):
  """Raised when a process receives SIGTERM and should terminate.

  The signal handler installed by procfn_wrap converts SIGTERM into this
  exception, so that the usual unwinding - cleanups included - happens
  before the process exits with code 1.
  """

procfn_wrap(procfn, *args, **kwargs)

Wrapper executed in the child process that sets up signals and cleanup.

Installs signal handlers, runs the target function, and ensures cleanup runs even on exceptions.

Parameters:

Name Type Description Default
procfn

The target function to execute.

required
*args

Positional arguments for procfn.

()
**kwargs

Keyword arguments for procfn.

{}

Returns:

Type Description

The return value of procfn.

Note

KeyboardInterrupt and TerminationError cause sys.exit(1); any other exception is logged - with the traceback - and re-raised.

Source code in py_misc_utils/multiprocessing.py
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
def procfn_wrap(procfn, *args, **kwargs):
  """Wrapper executed in the child process that sets up signals and cleanup.

  Installs signal handlers, runs the target function, and ensures cleanup
  runs even on exceptions.

  Args:
    procfn: The target function to execute.
    *args: Positional arguments for procfn.
    **kwargs: Keyword arguments for procfn.

  Returns:
    The return value of procfn.

  Note:
    KeyboardInterrupt and TerminationError cause sys.exit(1); any other
    exception is logged - with the traceback - and re-raised.
  """
  try:
    _process_setup()

    return procfn(*args, **kwargs)
  except (KeyboardInterrupt, TerminationError):
    sys.exit(1)
  except Exception as ex:
    alog.exception(ex, exmsg='Exception while running process function')
    raise
  finally:
    _process_cleanup()

create_process(procfn, args=(), kwargs=None, context=None, daemon=None)

Create a multiprocessing.Process with context propagation and signal handling.

The target is wrapped so that, in the child process, the parent global namespace state is restored (also with the spawn start method), SIGINT and SIGTERM install handlers - converting them to KeyboardInterrupt and TerminationError - and registered cleanups run on exit.

Example
import time
import py_misc_utils.multiprocessing as mpx

def slow_worker():
  time.sleep(5)

proc = mpx.create_process(slow_worker)
proc.start()
time.sleep(0.3)
proc.terminate()   # SIGTERM -> TerminationError -> exit code 1
proc.join(timeout=5)
assert proc.exitcode != 0

The target function is wrapped to propagate the parent's global namespace context, install signal handlers, and run cleanup on exit.

Parameters:

Name Type Description Default
procfn

The target function to execute in the child process.

required
args

Positional arguments passed to procfn.

()
kwargs

Keyword arguments passed to procfn.

None
context

Optional multiprocessing context, method name string, or None to use the default context.

None
daemon

Whether the process should be a daemon.

None

Returns:

Type Description

A multiprocessing.Process instance (not yet started).

Source code in py_misc_utils/multiprocessing.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
def create_process(procfn, args=(), kwargs=None, context=None, daemon=None):
  """Create a multiprocessing.Process with context propagation and signal handling.

  The target is wrapped so that, in the child process, the parent global
  namespace state is restored (also with the spawn start method), SIGINT
  and SIGTERM install handlers - converting them to KeyboardInterrupt and
  TerminationError - and registered cleanups run on exit.

  Example:
    import time
    import py_misc_utils.multiprocessing as mpx

    def slow_worker():
      time.sleep(5)

    proc = mpx.create_process(slow_worker)
    proc.start()
    time.sleep(0.3)
    proc.terminate()   # SIGTERM -> TerminationError -> exit code 1
    proc.join(timeout=5)
    assert proc.exitcode != 0

  The target function is wrapped to propagate the parent's global namespace
  context, install signal handlers, and run cleanup on exit.

  Args:
    procfn: The target function to execute in the child process.
    args: Positional arguments passed to procfn.
    kwargs: Keyword arguments passed to procfn.
    context: Optional multiprocessing context, method name string, or None
      to use the default context.
    daemon: Whether the process should be a daemon.

  Returns:
    A multiprocessing.Process instance (not yet started).
  """
  if context is None:
    mpctx = multiprocessing
  elif isinstance(context, str):
    mpctx = multiprocessing.get_context(method=context)
  else:
    mpctx = context

  kwargs = dict() if kwargs is None else kwargs.copy()

  kwargs = _capture_parent_context(mpctx.get_start_method(), kwargs)
  target = functools.partial(procfn_wrap, _wrapped_procfn, procfn, *args, **kwargs)

  return mpctx.Process(target=target, daemon=daemon)