Python提供了很是好用的多進程包multiprocessing,你只須要定義一個函數,Python會替你完成其餘全部事情。藉助這個包,能夠輕鬆完成從單進程到併發執行的轉換。併發
一、新建單一進程app
若是咱們新建少許進程,能夠以下:async
import multiprocessing import time def func(msg): for i in xrange(3): print msg time.sleep(1) if __name__ == "__main__": p = multiprocessing.Process(target=func, args=("hello", )) p.start() p.join() print "Sub-process done."
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import multiprocessing
import time
def func(msg):
for i in xrange(3):
print msg
time.sleep(1)
if __name__ == "__main__":
p = multiprocessing.Process(target=func, args=("hello", ))
p.start()
p.join()
print "Sub-process done."
|
二、使用進程池函數
是的,你沒有看錯,不是線程池。它能夠讓你跑滿多核CPU,並且使用方法很是簡單。spa
注意要用apply_async,若是落下async,就變成阻塞版本了。線程
processes=4是最多併發進程數量。code
import multiprocessing import time def func(msg): for i in xrange(3): print msg time.sleep(1) if __name__ == "__main__": pool = multiprocessing.Pool(processes=4) for i in xrange(10): msg = "hello %d" %(i) pool.apply_async(func, (msg, )) pool.close() pool.join() print "Sub-process(es) done."
三、使用Pool,並須要關注結果blog
更多的時候,咱們不只須要多進程執行,還須要關注每一個進程的執行結果,以下:進程
import multiprocessing import time def func(msg): for i in xrange(3): print msg time.sleep(1) return "done " + msg if __name__ == "__main__": pool = multiprocessing.Pool(processes=4) result = [] for i in xrange(10): msg = "hello %d" %(i) result.append(pool.apply_async(func, (msg, ))) pool.close() pool.join() for res in result: print res.get() print "Sub-process(es) done."