使用多处理模块:
import multiprocessing as mp
def print_mynumber(foo):
"""This function is obviously more complicated in my script.
It should be run as a subprocess."""
print(foo)
if __name__ == '__main__':
for foo in [1,2,3]:
proc = mp.Process(target = print_mynumber, args = (foo, ))
proc.start()
您可能不想为每次调用创建一个进程print_mynumber
,尤其是在列表foo
迭代很长的情况下。在这种情况下,更好的方法是使用多处理池:
import multiprocessing as mp
def print_mynumber(foo):
"""This function is obviously more complicated in my script.
It should be run as a subprocess."""
print(foo)
if __name__ == '__main__':
pool = mp.Pool()
pool.map(print_mynumber, [1,2,3])
The pool, be default, will create N worker processes, where N
is the number of cpus (or cores) the machine possesses. pool.map
behaves much like the Python builtin map
command, except that it farms out tasks to the pool of workers.