python 多線程中join()的作用
一 前言
溫習(xí)python 多進(jìn)程語法的時(shí)候,對(duì) join的理解不是很透徹,本文通過代碼實(shí)踐來加深對(duì) join()的認(rèn)識(shí)。
multiprocessing 是python提供的跨平臺(tái)版本的多進(jìn)程模塊。multiprocessing可以充分利用多核,提升程序運(yùn)行效率。multiprocessing支持子進(jìn)程,通信和共享數(shù)據(jù),執(zhí)行不同形式的同步,提供了Process、Queue、Pipe、Lock等組件。不過今天重點(diǎn)了解 join。后續(xù)文章會(huì)逐步學(xué)習(xí)介紹其他組件或者功能。
二 動(dòng)手實(shí)踐
join()方法可以在當(dāng)前位置阻塞主進(jìn)程,帶執(zhí)行join()的進(jìn)程結(jié)束后再繼續(xù)執(zhí)行主進(jìn)程的代碼邏輯。
# encoding: utf-8'''author: yangyi@youzan.comtime: 2019/7/30 11:20 AMfunc:'''from multiprocessing import Processimport osimport timedef now(): return str(time.strftime(’%Y-%m-%d %H:%M:%S’, time.localtime()))def func_1(name): print(now() + ’ Run child process %s (%s)...’ % (name, os.getpid())) time.sleep(4) print(now() + ’ Stop child process %s (%s)...n’ % (name, os.getpid()))def func_2(name): print(now() + ’ Run child process %s (%s)...’ % (name, os.getpid())) time.sleep(8) print(now() + ’ hello world!’) print(now() + ’ Stop child process %s (%s)...n’ % (name, os.getpid()))if __name__ == ’__main__’: print (’Parent process %s.’ % os.getpid()) p1 = Process(target=func_1, args=(’func_1’,)) p2 = Process(target=func_2, args=(’func_2’,)) print now() + ’ Process start.’ p1.start() p2.start() p1.join() p2.join() print now() + ’ Process end .’
輸出結(jié)果
結(jié)果顯示
主進(jìn)程的 Process end .是在func1 和func2 結(jié)束之后才打印出來的。
2.2 去掉 join() 函數(shù)
if __name__ == ’__main__’: print (’Parent process %s.’ % os.getpid()) p1 = Process(target=func_1, args=(’func_1’,)) p2 = Process(target=func_2, args=(’func_2’,)) print now() + ’ Process start.’ p1.start() p2.start() print now() + ’ Process end .’
結(jié)果如下:
2.3 去掉func_2 的 join()
if __name__ == ’__main__’: print (’Parent process %s.’ % os.getpid()) p1 = Process(target=func_1, args=(’func_1’,)) p2 = Process(target=func_2, args=(’func_2’,)) print now() + ’ Process start.’ p1.start() p2.start() p1.join() ### 在p1 執(zhí)行完之后 。不等待p2 執(zhí)行,主進(jìn)程結(jié)束。 print now() + ’ Process end .’
結(jié)果如下:
結(jié)果顯示主線程 'Process end'在func_1 執(zhí)行結(jié)束之后輸出而沒有等待func_2 執(zhí)行完畢。
2.4 小結(jié)
利用多線程時(shí),一般都先讓子線程調(diào)用start() ,然后再去調(diào)用join(),讓主進(jìn)程等待子進(jìn)程結(jié)束才繼續(xù)走后續(xù)的邏輯。
思考題
能不能每個(gè)子進(jìn)程調(diào)用start() 之后,然后直接調(diào)用join() 類似:
p1.start()p1.join()p2.start()p2.join()
以上就是python 多線程中join()的作用的詳細(xì)內(nèi)容,更多關(guān)于python 多線程join()的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP字符串前后字符或空格刪除方法介紹2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法4. nestjs實(shí)現(xiàn)圖形校驗(yàn)和單點(diǎn)登錄的示例代碼5. python開發(fā)飛機(jī)大戰(zhàn)游戲6. laravel ajax curd 搜索登錄判斷功能的實(shí)現(xiàn)7. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式8. css進(jìn)階學(xué)習(xí) 選擇符9. Echarts通過dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖10. python實(shí)現(xiàn)自動(dòng)化辦公郵件合并功能
