python threading模塊的使用指南
接上述案例,我們可以利用程序阻塞的時間讓程序執(zhí)行后面的任務(wù),可以用多線程的方式去實現(xiàn)。對應(yīng)的需要我們借助threading模塊去實現(xiàn):如下所示
import timeimport threadingdef work():'''只有函數(shù)對象才能?煙錈?呋?''print(’5.洗茶杯: 1min ’ )time.sleep(1)print(’6.放茶葉: 1min ’ )time.sleep(1)start_time = time .time()print( ’1.洗壺: 1min ’ )time.s1eep(1)print( ’2.灌涼水:1min ’ )time.sleep(1)print( ’3.燒水: 1min ’ )time.sleep(1)print( ’4.等水燒開:3min ’ )work_thread = threading.Thread(target=work)# 啟動線程對象work_thread.start()time.sleep(1) # 5.洗茶杯: 1mintime.sleep(1) # 6.放茶葉: 1mintime.sleep(1)print( ’7.泡茶:1min ’ )time.sleep(1)print(’總共花了: ’,time.time() - start_time)
以上案例是一個單線程,需要特別注意的是threading模塊操作線程所操作的必須是函數(shù)對象。通過threding模塊可以把一個普通的函數(shù)對象轉(zhuǎn)化為線程對象。
2. threding模塊創(chuàng)建多線程當(dāng)一個進程啟動之后,會默認產(chǎn)生一個主線程,因為線程是程序執(zhí)行流的最小單元,當(dāng)設(shè)置多線程時,主線程會創(chuàng)建多個子線程,在python中,默認情況下,主線程執(zhí)行完自己的任務(wù)以后,就退出了,此時子線程會繼續(xù)執(zhí)行自己的任務(wù),直到自己的任務(wù)結(jié)束。
import timeimport threadingdef upload():print('開始上傳文件...')time.sleep(2)print('完成上傳文件...')def down1oad():print('開始下載文件...')time.s1eep(2)print('完成下載文件...')if __name__ == ’__main__’:upload_thread = threading.Thread(target=up1oad)up1oad_thread .start()up1oad_thread.join()down1oad_thread = threading.Thread(target=down1oad,daemon=True)down1oad_thread.start()print(’主線程結(jié)束’)
也就是說主線程在分配任務(wù)時會創(chuàng)建多個子線程,子線程的任務(wù)進度不會阻礙主線程的執(zhí)行。但是主線程會等待子線程執(zhí)行任務(wù)完之后才結(jié)束主線程。也就是說實際上主線程是先執(zhí)行完任務(wù)的,如果你想在主線程執(zhí)行完之后就結(jié)束整個線程的話,那么可以設(shè)置守護主線程。
3. 多線程的參數(shù)傳遞多線程的參數(shù)傳遞用args接受位置參數(shù),用kwargs接受關(guān)鍵字參數(shù)。如下所示:
import threadingdef get(ur1,header=None): print(ur1) print(header)for url in [ ’https : / /www.baidu.com’, ’https:/ /www. soso.com ’ ,’ https: / /www . 360. com’]: # threading.Threadget_thread = threading. Thread(target=get,args=(ur1, ), kwargs={ ’ header ’:{ ’user-agent ’ : ’ pythonrequests’}}) get_thread.start4. 線程產(chǎn)生的資源競爭
首先我們來看一個案例:
import threadingimport timeimport randomdef add1(n): for i in range(100) :time.sleep(random.randint(1,3))with open( ’he7lo.txt’, mode=’a’, encoding=’utf-8 ’ ) as f: f.write(f’in} he1lo wor1d !’+ ’he7lo wor1d !’*1024) f.write(’ n ’)if __name__ == ’___main__’ : for n in range(10) :t1 = threading. Thread(target=add1,args=(n,))t1.start()
以上就是python threading模塊的使用指南的詳細內(nèi)容,更多關(guān)于python threading模塊的使用的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實現(xiàn)方法2. docker compose idea CreateProcess error=2 系統(tǒng)找不到指定的文件的問題3. 一文秒懂idea的git插件跟翻譯插件4. Java反射技術(shù)原理與用法實例分析5. vue中使用echarts的示例6. python爬蟲利用代理池更換IP的方法步驟7. JS算法題解旋轉(zhuǎn)數(shù)組方法示例8. python中pandas.read_csv()函數(shù)的深入講解9. Vue+express+Socket實現(xiàn)聊天功能10. JS中的常見數(shù)組遍歷案例詳解(forEach, map, filter, sort, reduce, every)
