Python中threading模塊的join函數

Join的作用是衆所周知的,阻塞進程直到線程執行完畢。通用的做法是我們啓動一批線程,最後join這些線程結束,例如:

for i in range(10):
    t = ThreadTest(i)
    thread_arr.append(t)

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的超時。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章