天天看点

python如何同时运行两个函数_Python:如何并行运行python函数?

如果您是Windows用户并使用python 3,那么这篇文章将帮助您在python中进行并行编程。当您运行通常的多处理库的池编程时,您将收到有关程序中主函数的错误。这是因为windows没有fork()功能。以下帖子正在解决上述问题。

由于我使用的是python 3,我将程序改为:from types import FunctionTypeimport marshaldef _applicable(*args, **kwargs):

name = kwargs['__pw_name']

code = marshal.loads(kwargs['__pw_code'])

gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])

defs = marshal.loads(kwargs['__pw_defs'])

clsr = marshal.loads(kwargs['__pw_clsr'])

fdct = marshal.loads(kwargs['__pw_fdct'])

func = FunctionType(code, gbls, name, defs, clsr)

func.fdct = fdct del kwargs['__pw_name']

del kwargs['__pw_code']

del kwargs['__pw_defs']

del kwargs['__pw_clsr']

del kwargs['__pw_fdct']

return func(*args, **kwargs)def make_applicable(f, *args, **kwargs):

if not isinstance(f, FunctionType): raise ValueError('argument must be a function')

kwargs['__pw_name'] = f.__name__ # edited

kwargs['__pw_code'] = marshal.dumps(f.__code__) # edited

kwargs['__pw_defs'] = marshal.dumps(f.__defaults__) # edited

kwargs['__pw_clsr'] = marshal.dumps(f.__closure__) # edited

kwargs['__pw_fdct'] = marshal.dumps(f.__dict__) # edited

return _applicable, args, kwargsdef _mappable(x):

x,name,code,defs,clsr,fdct = x

code = marshal.loads(code)

gbls = globals() #gbls = marshal.loads(gbls)

defs = marshal.loads(defs)

clsr = marshal.loads(clsr)

fdct = marshal.loads(fdct)

func = FunctionType(code, gbls, name, defs, clsr)

func.fdct = fdct return func(x)def make_mappable(f, iterable):

if not isinstance(f, FunctionType): raise ValueError('argument must be a function')

name = f.__name__ # edited

code = marshal.dumps(f.__code__) # edited

defs = marshal.dumps(f.__defaults__) # edited

clsr = marshal.dumps(f.__closure__) # edited

fdct = marshal.dumps(f.__dict__) # edited

return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)

在这个函数之后,上面的问题代码也改变了一点:from multiprocessing import Poolfrom poolable import make_applicable, make_mappabledef cube(x):

return x**3if __name__ == "__main__":

pool = Pool(processes=2)

results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]

print([result.get(timeout=10) for result in results])

我得到的输出为:[1, 8, 27, 64, 125, 216]

我认为这篇文章可能对某些Windows用户有用。