procs (version dev) | index /home/lenny/domnit.org/home/htdocs/procs/procs.py |
Run Python functions in parallel processes
Parallel child processes cannot affect in-memory state of the parent
or sibling processes, so procs is best suited for parallelizing
functional-style programs.
Procs uses pickle to share objects between processes.
Example usage:
from procs import *
# Some dummy functions we'll use below. Realistically, procs has
# too much overhead to be useful for such small functions.
def f(x, y):
return 5 * x + 3 * y
def g(n):
return n + 4
# Using call to run 4 processes in parallel:
proc_specs = [ # Process specifications equivalent to:
proc(f, 2, 7), # f(2, 7)
proc(f, x=-3, y=8), # f(x=-3, y=8)
proc(g, 38), # g(38)
proc(g, n=95) # g(n=95)
]
vals = call(proc_specs) # Now the functions are actually called
print list(vals) # [31, 9, 42, 99]
# Using pmap as a process-parallelized version of Python's map:
vals = pmap(f, [12, 75, -2, 9], [5, -6, 0, 23])
print list(vals) # [75, 357, -10, 114]
# Careful. Objects are pickled and copied:
x = object()
y = (lambda obj: obj)(x)
print x is y # True
z = call([proc((lambda obj: obj), x)]).next()
print x is z # False
Exception handling:
# When an error occurs in a worker process, a traceback is
# printed, but all processes finish and yield a value. Failed
# processes yield an instance of the procs.Failed exception, with
# the original exception as its arguments.
def double_odd(x):
if x % 2 == 1:
return x + x
else:
raise ValueError('not odd', x)
print list(procs.pmap(double_odd, [1, 3, 6, 7]))
# [2, 6, Failed(ValueError('not odd', 6),), 14]
Modules | ||||||
|
Classes | ||||||||
|
Functions | ||
|
Data | ||
__all__ = ('proc', 'call', 'pmap', 'Failed') __author__ = 'Lenny Domnitser <http://domnit.org/>' __version__ = 'dev' |
Author | ||
Lenny Domnitser <http://domnit.org/> |