Python中threading模組的join函數

來源:互聯網
上載者:User

標籤:

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

 1 for i in range(10): 2  3     t = ThreadTest(i) 4  5     thread_arr.append(t) 6  7 for i in range(10): 8  9     thread_arr[i].start()10 11 for i in range(10):12 13     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模組的join函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.