目錄
- 1. threding模塊創建線程對象
- 2. threding模塊創建多線程
- 3. 多線程的參數傳遞
- 4. 線程產生的資源競爭
1. threding模塊創建線程對象
接上述案例,我們可以利用程序阻塞的時間讓程序執行后面的任務,可以用多線程的方式去實現。對應的需要我們借助threading模塊去實現:
如下所示
import time
import threading
def work():
"""只有函數對象才能佈田名線積"""
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模塊操作線程所操作的必須是函數對象。通過threding模塊可以把一個普通的函數對象轉化為線程對象。
2. threding模塊創建多線程
當一個進程啟動之后,會默認產生一個主線程,因為線程是程序執行流的最小單元,當設置多線程時,主線程會創建多個子線程,在python中,默認情況下,主線程執行完自己的任務以后,就退出了,此時子線程會繼續執行自己的任務,直到自己的任務結束。
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('主線程結束')
也就是說主線程在分配任務時會創建多個子線程,子線程的任務進度不會阻礙主線程的執行。但是主線程會等待子線程執行任務完之后才結束主線程。也就是說實際上主線程是先執行完任務的,如果你想在主線程執行完之后就結束整個線程的話,那么可以設置守護主線程。
3. 多線程的參數傳遞
多線程的參數傳遞用args接受位置參數,用kwargs接受關鍵字參數。如下所示:
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. 線程產生的資源競爭
首先我們來看一個案例:
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模塊的使用指南的詳細內容,更多關于python threading模塊的使用的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- Python threading.local代碼實例及原理解析
- python語言線程標準庫threading.local解讀總結
- Python中threading庫實現線程鎖與釋放鎖
- python中threading和queue庫實現多線程編程
- Python threading Local()函數用法案例詳解