13.1 threading 模塊和 Thread 對(duì)象

?????

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')

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容