1、新建单一进程
如果我们新建少量进程,可以如下:
import multiprocessing
import time
def func(msg):
for i in range(3):
print(msg)
time.sleep(1)
if __name__ == "__main__":
p = multiprocessing.Process(target=func, args=("hello", ))
p.start()
p.join()
print("Sub-process done.")
2、使用进程池
这不是线程池,这个可以将多核CPU全部跑满,非常的刺激,而且使用起来也超级简单。但是一定要用apply_async,如下所示:
import multiprocessing
import time
def func(msg):
for i in range(3):
print(msg)
time.sleep(1)
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=10)
for i in range(10):
msg = "hello %d" %(i)
pool.apply_async(func, (msg, ))
pool.close()
pool.join()
print("Sub-process(es) done.")
网友评论