Python中threading模組的join函式

2021-09-02 03:32:29 字數 763 閱讀 6436

oin的作用是眾所周知的,阻塞程序直到執行緒執行完畢。通用的做法是我們啟動一批執行緒,最後join這些執行緒結束,例如:

for i in range(10):

t = threadtest(i)

for i in range(10):

thread_arr[i].start()

for i in range(10):

thread_arr[i].join()

此處join的原理就是依次檢驗執行緒池中的執行緒是否結束,沒有結束就阻塞直到執行緒結束,如果結束則跳轉執行下乙個執行緒的join函式。

而py的join函式還有乙個特殊的功能就是可以設定超時,如下:

thread.join([timeout])

wait until the thread terminates. this blocks the calling thread until the thread whose join()

method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

也就是通過傳給join乙個引數來設定超時,也就是超過指定時間join就不在阻塞程序。而在實際應用測試的時候發現並不是所有的執行緒在超時時間內都結束的,而是順序執行檢驗是否在time_out時間內超時,例如,超時時間設定成2s,前面乙個執行緒在沒有完成的情況下,後面執行緒執行join會從上乙個執行緒結束時間起再設定2s的超時。

python中的執行緒使用 threading模組

最近又用到了python中的多執行緒程式設計,前段時間使用並學習過,但是由於長時間不用,慢慢就忘記怎麼用了,畢竟對執行緒的使用還不是很熟練,現在總結一下,記錄下來,加深一下學習的印象。python中關於執行緒,主要有兩個模組thread和threading,其中thread的模組已不建議使用,因為t...

11 2 Python多執行緒threading

分程序設定 工具 threading包 1 先寫需要分程序執行的函式或者類 defmaigic pass 2 例項化threading,得到新的程序 threadone threading.thread target maigic 此時還可以接受arg引數import threading impor...

Python3併發程式設計之threading模組

建立執行緒物件 threading.thread 引數 引數 描述group none 該類中的待擴充套件引數。target none 目標函式,即被開闢執行緒的執行任務。預設值為none,表示什麼都不執行。name none 該執行緒的名稱。在預設情況下,執行緒的唯一名稱以 thread n 的形...