簡介
Python 通過 _thread 和 threading 模塊提供了對多線程的支持,threading 模塊兼具了 _thread 模塊的現有功能,又擴展了一些新的功能,具有十分豐富的線程操作功能
創建線程
使用 threading 模塊創建線程通常有兩種方式:
1)使用 threading 模塊中 Thread 類的構造器創建線程,即直接對類 threading.Thread 進行實例化,并調用實例化對象的 start 方法創建線程;
2)繼承 threading 模塊中的 Thread 類創建線程類,即用 threading.Thread 派生出一個新的子類,將新建類實例化,并調用其 start 方法創建線程。
構造器方式
調用 threading.Thread 類的如下構造器創建線程:
threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
group:指定該線程所屬的線程組,目前該參數還未實現,為了日后擴展 ThreadGroup 類實現而保留。
target:用于 run() 方法調用的可調用對象,默認是 None,表示不需要調用任何方法。
args:是用于調用目標函數的參數元組,默認是 ()。
kwargs:是用于調用目標函數的關鍵字參數字典,默認是 {}。
daemon:如果 daemon 不是 None,線程將被顯式的設置為守護模式,不管該線程是否是守護模式,如果是 None (默認值),線程將繼承當前線程的守護模式屬性。
import time
import threading
def work(num):
print('線程名稱:',threading.current_thread().getName(),'參數:',num,'開始時間:',time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == '__main__':
print('主線程開始時間:',time.strftime('%Y-%m-%d %H:%M:%S'))
t1 = threading.Thread(target=work,args=(3,))
t2 = threading.Thread(target=work,args=(2,))
t3 = threading.Thread(target=work,args=(1,))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
print('主線程結束時間:', time.strftime('%Y-%m-%d %H:%M:%S'))
上述示例中實例化了三個 Thread 類的實例,并向任務函數傳遞不同的參數,start
方法開啟線程,join
方法阻塞主線程,等待當前線程運行結束。
繼承方式
通過繼承的方式創建線程包括如下步驟:1)定義 Thread 類的子類,并重寫該類的 run 方法;2)創建 Thread 子類的實例,即創建線程對象;3)調用線程對象的 start 方法來啟動線程。示例如下:
import time
import threading
class MyThread(threading.Thread):
def __init__(self,num):
super().__init__()
self.num = num
def run(self):
print('線程名稱:', threading.current_thread().getName(), '參數:', self.num, '開始時間:', time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == '__main__':
print('主線程開始時間:',time.strftime('%Y-%m-%d %H:%M:%S'))
t1 = MyThread(3)
t2 = MyThread(2)
t3 = MyThread(1)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
print('主線程結束時間:', time.strftime('%Y-%m-%d %H:%M:%S'))
上述示例中自定義了線程類 MyThread,繼承了 threading.Thread,并重寫了 __init__ 方法和 run 方法。
守護線程
守護線程(也稱后臺線程)是在后臺運行的,它的任務是為其他線程提供服務,如 Python 解釋器的垃圾回收線程就是守護線程。如果所有的前臺線程都死亡了,守護線程也會自動死亡。來看個例子:
# 不設置守護線程
import threading
def work(num):
for i in range(num):
print(threading.current_thread().name + " " + str(i))
t = threading.Thread(target=work, args=(10,), name='守護線程')
t.start()
for i in range(10):
pass
# 設置守護線程
import threading
def work(num):
for i in range(num):
print(threading.current_thread().name + " " + str(i))
t = threading.Thread(target=work, args=(10,), name='守護線程')
t.daemon = True
t.start()
for i in range(10):
pass
上述示例直觀的說明了當前臺線程結束,守護線程也會自動結束。
如果你設置一個線程為守護線程,就表示這個線程是不重要的,在進程退出的時候,不用等待這個線程退出;如果你的主線程在退出的時候,不用等待哪些子線程完成,那就設置這些線程為守護線程;如果你想等待子線程完成后再退出,那就什么都不用做,或者顯示地將 daemon 屬性設置為 false。
線程本地數據
Python 的 threading 模塊提供了 local 方法,該方法返回得到一個全局對象,不同線程使用這個對象存儲的數據,其它線程是不可見的(本質上就是不同的線程使用這個對象時為其創建一個獨立的字典)。來看個示例:
# 不使用 threading.local
import threading
import time
num = 0
def work():
global num
for i in range(10):
num += 1
print(threading.current_thread().getName(), num)
time.sleep(0.0001)
for i in range(5):
threading.Thread(target=work).start()
上面示例中 num 是全局變量,變成了公共資源,通過輸出結果,我們發現子線程之間的計算結果出現了互相干擾的情況。
# 使用 threading.local
num = threading.local()
def work():
num.x = 0
for i in range(10):
num.x += 1
print(threading.current_thread().getName(), num.x)
time.sleep(0.0001)
for i in range(5):
threading.Thread(target=work).start()
使用 threading.local 的示例中,num 是全局變量,但每個線程定義的屬性 num.x 是各自線程獨有的,其它線程是不可見的,因此每個線程的計算結果未出現相互干擾的情況。
定時器
threading 模塊提供了 Timer 類實現定時器功能,來看個例子:
# 單次執行
from threading import Timer
def work():
print("Hello Python")
# 5 秒后執行 work 方法
t = Timer(5, work)
t.start()
Timer 只能控制函數在指定的時間內執行一次,如果我們需要多次重復執行,需要再進行一次調度,想要取消調度時可以使用 Timer 的 cancel 方法。來看個例子:
# 重復執行
count = 0
def work():
print('當前時間:', time.strftime('%Y-%m-%d %H:%M:%S'))
global t, count
count += 1
# 如果 count 小于 5,開始下一次調度
if count 5:
t = Timer(1, work)
t.start()
# 指定 2 秒后執行 work 方法
t = Timer(2, work)
t.start()
以上就是Python 多線程之threading 模塊的使用的詳細內容,更多關于python threading的使用的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- Python中threading庫實現線程鎖與釋放鎖
- Python多線程編程之threading模塊詳解
- python中threading和queue庫實現多線程編程
- Python threading模塊condition原理及運行流程詳解
- Python多線程threading創建及使用方法解析
- Python3 socket即時通訊腳本實現代碼實例(threading多線程)
- Python中使用threading.Event協調線程的運行詳解
- python繼承threading.Thread實現有返回值的子類實例
- 淺談Python中threading join和setDaemon用法及區別說明
- python中threading開啟關閉線程操作
- python threading模塊的使用指南