python中得thread的一些機制和C/C++不同:在C/C++中,主線程結束後,其子線程會默認被主線程kill掉。而在python中,主線程結束後,會默認等待子線程結束後,主線程才退出。
python對於thread的管理中有兩個函數:join和setDaemon
- join:如在一個線程B中調用threada.join(),則threada結束後,線程B纔會接着threada.join()往後運行。
- setDaemon:主線程A啓動了子線程B,調用b.setDaemaon(True),則主線程結束時,會把子線程B也殺死,與C/C++中得默認效果是一樣的。
在這裏給出一個例子:
<span style="color:#ffffff;"> </span><span style="color:#330033;">1 #! /usr/bin/env python
2
3 import threading
4 import time
5
6 class myThread(threading.Thread):
7 def __init__(self, threadname):
8 threading.Thread.__init__(self, name=threadname)
9 self.st = 2
10
11 def run(self):
12 time.sleep(self.st)
13 print self.getName()
14 def setSt(self, t):
15 self.st = t
16
17 def fun1():
18 t1.start()
19 print "fun1 done"
20
21 def fun2():
22 t2.start()
23 print "fun2 done"
24
25 t1=myThread("t1")
26 t2=myThread("t2")
27 t2.setSt(10);
28 # t2.setDaemon(True)
29 fun1()
30 fun2()
31 print "now u will see me"</span>