这是一个如何并行调用函数的示例。从In [10]: p1.start()你可以看到输出变得混乱,因为程序p1在我们运行程序p2时并行运行。在
在Python脚本中运行程序时,要确保脚本只在所有程序都成功执行之后才结束。你可以通过
^{pr2}$
由于吉尔,Python没有C++或类似java的多线程支持。Read about it here。不过,如果你的程序执行的I/O操作比CPU密集型任务多,那么你可以使用多线程。对于执行CPU密集型任务,建议使用多处理。在
在评论中@ytutow问到工人池和过程之间有什么区别。从Pymotw:The Pool class can be used to manage a fixed number of workers for
simple cases where the work to be done can be broken up and
distributed between workers independently.
The return values from the jobs are collected and returned as a list.
The pool arguments include the number of processes and a function to
run when starting the task process (invoked once per child).
您可以将池用作:def your_instance_method(instance):
instances.do_some_computation_over_a_dataset()
with Pool(3) as p:
instances = [insatnce_1, instance_2, instance_3]
print(p.map(your_instance_method, instances))
关于正确的工作线程数,一般建议使用2*cpu内核的工作线程数。在