multiprocessing中Pool實現異步#
關于異步與同步可以做一個例子來解釋一下。
拿爬蟲為例,目前需要爬取京東、淘寶網站。同步的方法是,首先我要爬取京東網站,發(fā)送請求后等待京東網站返回它的數據,然后再爬取淘寶,再等待它返回的數據。同步是有一定順序性的。
異步的方式是,首先我同時向京東和淘寶兩個網站發(fā)送請求,此時誰先返回數據先處理誰。由于存在了不確定性,所以這種方式可以理解為是異步的一種行為。
使用multiprocessing中Pool來實現異步,使用的是Pool中callback的功能。
實現代碼如下:
#coding=utf-8
from multiprocessing import Pool
import os,time
def test():
print('test進程pid=%s,ppid=%s'%(os.getpid(),os.getppid()))
return 'hello world'
time.sleep(1)
def test2(args):
print('test2進程pid=%s,ppid=%s'%(os.getpid(),os.getppid()))
print(args)
time.sleep(1)
if __name__ == '__main__':
pool = Pool()
pool.apply_async(func = test,callback = test2)
# pool.close()
# pool.join()
while True:
print('主進程pid=%s,ppid=%s'%(os.getpid(),os.getppid()))
time.sleep(1)
運行結果如下:
從這里我們可以發(fā)現,當callback = test2的時候,其實是通過主進程完成的。其中test()中的返回值被test2()作為參數調用,如果test()沒有返回值的話,那么test2()需要將self傳入,例如test2(self)