python threading模塊的使用指南
1. threding模塊創(chuàng)建線程對象
接上述案例,我們可以利用程序阻塞的時(shí)間讓程序執(zhí)行后面的任務(wù),可以用多線程的方式去實(shí)現(xiàn)。對應(yīng)的需要我們借助threading模塊去實(shí)現(xiàn):
如下所示
import time
import threading
def 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.洗茶杯: 1min
time.sleep(1) # 6.放茶葉: 1min
time.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)一個進(jìn)程啟動之后,會默認(rèn)產(chǎn)生一個主線程,因?yàn)榫€程是程序執(zhí)行流的最小單元,當(dāng)設(shè)置多線程時(shí),主線程會創(chuàng)建多個子線程,在python中,默認(rèn)情況下,主線程執(zhí)行完自己的任務(wù)以后,就退出了,此時(shí)子線程會繼續(xù)執(zhí)行自己的任務(wù),直到自己的任務(wù)結(jié)束。
import time
import threading
def 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ù)時(shí)會創(chuàng)建多個子線程,子線程的任務(wù)進(jìn)度不會阻礙主線程的執(zhí)行。但是主線程會等待子線程執(zhí)行任務(wù)完之后才結(jié)束主線程。也就是說實(shí)際上主線程是先執(zhí)行完任務(wù)的,如果你想在主線程執(zhí)行完之后就結(jié)束整個線程的話,那么可以設(shè)置守護(hù)主線程。
3. 多線程的參數(shù)傳遞
多線程的參數(shù)傳遞用args接受位置參數(shù),用kwargs接受關(guān)鍵字參數(shù)。如下所示:
import threading
def get(ur1,header=None):
print(ur1)
print(header)
for url in [ 'https : / /www.baidu.com', 'https:/ /www. soso.com ' ,' https: / /www . 360. com']:
# threading.Thread
get_thread = threading. Thread(target=get,args=(ur1, ), kwargs={ ' header ':{ 'user-agent ' : ' pythonrequests'}})
get_thread.start
4. 線程產(chǎn)生的資源競爭
首先我們來看一個案例:
import threading
import time
import random
def 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模塊的使用指南的詳細(xì)內(nèi)容,更多關(guān)于python threading模塊的使用的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信