python多線程編程(8):線程的合並和后台線程


線程的合並

python的Thread類中還提供了join()方法,使得一個線程可以等待另一個線程執行結束后再繼續運行。這個方法還可以設定一個timeout參數,避免無休止的等待。因為兩個線程順序完成,看起來象一個線程,所以稱為線程的合並。一個例子:

import threading
import random
import time

class MyThread(threading.Thread):

def run(self):
wait_time=random.randrange(1,10)
print "%s will wait %d seconds" % (self.name, wait_time)
time.sleep(wait_time)
print "%s finished!" % self.name

if __name__=="__main__":
threads = []
for i in range(5):
t = MyThread()
t.start()
threads.append(t)
print 'main thread is waitting for exit...'
for t in threads:
t.join(1)

print 'main thread finished!'

執行結果:

Thread-1 will wait 3 seconds
Thread-2 will wait 4 seconds
Thread-3 will wait 1 seconds
Thread-4 will wait 5 seconds
Thread-5 will wait 3 seconds
main thread is waitting for exit...
Thread-3 finished!
Thread-1 finished!
Thread-5 finished!
main thread finished!
Thread-2 finished!
Thread-4 finished!

對於sleep時間過長的線程(這里是2和4),將不被等待。

后台線程

默認情況下,主線程在退出時會等待所有子線程的結束。如果希望主線程不等待子線程,而是在退出時自動結束所有的子線程,就需要設置子線程為后台線程(daemon)。方法是通過調用線程類的setDaemon()方法。如下:

import threading
import random
import time

class MyThread(threading.Thread):

def run(self):
wait_time=random.randrange(1,10)
print "%s will wait %d seconds" % (self.name, wait_time)
time.sleep(wait_time)
print "%s finished!" % self.name

if __name__=="__main__":
print 'main thread is waitting for exit...'

for i in range(5):
t = MyThread()
t.setDaemon(True)
t.start()

print 'main thread finished!'

執行結果:

main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
 Thread-4 will wait 7 seconds
 Thread-5 will wait 7 seconds
main thread finished!

可以看出,主線程沒有等待子線程的執行,而直接退出。

小結

join()方法使得線程可以等待另一個線程的運行,而setDaemon()方法使得線程在結束時不等待子線程。join和setDaemon都可以改變線程之間的運行順序。


免責聲明!

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



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