?????
13.1 threading 模塊

BC3BA70FAEE8FE851CA38B0C49F897CA.jpg
????? 簡(jiǎn)單演示該模塊方法:
>>> import threading
>>> threading.stack_size() # 查看當(dāng)前線程棧大小
0
>>> threading.stack_size(64 * 1024) # 設(shè)置當(dāng)前線程棧大小
0
>>> threading.active_count() # 當(dāng)前活動(dòng)線程數(shù)量
2
>>> threading.current_thread() # 當(dāng)前線程對(duì)象
<_MainThread(MainThread, started 13100)>
>>> threading.enumerate() # 當(dāng)前活動(dòng)線程對(duì)象列表
[<_MainThread(MainThread, started 13100)>, <Thread(SockThread, started daemon 10460)>]
13.2.1 Thread 對(duì)象中的方法
????? Thread 類創(chuàng)建線程對(duì)象,調(diào)用其 start() 方法來(lái)啟動(dòng),該方法自動(dòng)調(diào)用該類對(duì)象的 run() 方法,此時(shí)該線程處于 alive 狀態(tài),直到 run() 方法運(yùn)行結(jié)束。

2C59040A0A67981D2B7D841B6CD394E5.jpg
(1)join([timeout)) :阻塞當(dāng)前線程,等待被調(diào)線程結(jié)束或超時(shí)后再執(zhí)行當(dāng)前線程的后續(xù)代碼。
import threading
import time
def func(x, y):
for i in range(x, y):
print(i, end = ' ')
time.sleep(10)
t1 = threading.Thread(target = func, args = (15, 20))
t1.start()
t1.join(5)
t2 = threading.Thread(target = func, args = (5, 10))
t2.start()
(2)is_alive() :測(cè)試線程是否處于運(yùn)行狀態(tài)。
import threading
import time
def func(x, y):
for i in range(x, y):
print(i, end = ' ')
# time.sleep(10)
t1 = threading.Thread(target = func, args = (15, 20))
t1.start()
t1.join(5)
t2 = threading.Thread(target = func, args = (5, 10))
t2.start()
print('t1:', t1.is_alive())
print('t2:', t2.is_alive())
13.2.2 Thread 對(duì)象中的 daemon 屬性
????? 當(dāng)某子線程的 daemon 屬性為 True 時(shí),主線程運(yùn)行結(jié)束時(shí)不對(duì)該子線程進(jìn)行檢查直接退出,同時(shí)所有 daemon 值為 True 的子線程將隨主線程一切結(jié)束,不論是否完成。daemon 屬性默認(rèn)為 False,如需修改,必須在 start() 方法之前修改。
import threading
import time
class mythread(threading.Thread):
def __init__(self, num, threadname):
threading.Thread.__init__(self, name = threadname)
self.num = num
def run(self):
time.sleep(self.num)
print(self.num)
t1 = mythread(1, 't1')
t2 = mythread(5, 't2')
t2.daemon = True
print(t1.daemon)
print(t2.daemon)
t1.start()
t2.start()
????? 派生自 Thread 類的自定義線程類首先也是一個(gè)普通類,同時(shí)擁有線程類的 run()、start()、join()等方法。
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadName):
threading.Thread.__init__(self)
self.name = threadName
def run(self):
time.sleep(1)
print('In run:', self.name)
def output(self): # 在線程類中定義普通方法
print('In output:', self.name)
t = myThread('test')
t.start()
t.output() # 調(diào)用普通方法
time.sleep(2)
print('OK')