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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM