Join的作用是衆所周知的,阻塞程序直到線程執行完畢。通用的做法是我們啟動一批線程,最後join這些線程結束,例如:
<code>for</code> <code>i </code><code>in</code> <code>range</code><code>(</code><code>10</code><code>):</code>
<code> </code><code>t </code><code>=</code> <code>ThreadTest(i)</code>
<code> </code><code>thread_arr.append(t)</code>
<code> </code><code>thread_arr[i].start()</code>
<code> </code><code>thread_arr[i].join()</code>
此處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的逾時。
本文轉自 奚落123 51CTO部落格,原文連結:http://blog.51cto.com/guyuyuan/1927175,如需轉載請自行聯系原作者