python threading中處理主進程和子線程的關係
之前用Python的多線程,總是處理不好進程和線程之間的關係。後來發現了join和setDaemon函數,才終於弄明白。下面總結一下。
1.使用join函數後,主進程會在調用join的地方等待子線程結束,然後才接著往下執行。
join使用實例如下:
[python] view plain copy
import
time
import
randomimport
threadingclass
worker(threading.Thread):def
__init__(self):- threading.Thread.__init__(self)
def
run(self):- t = random.randint(1,10)
- time.sleep(t)
print
"This is " + self.getName() + ";I sleep %d second."%(t)- tsk = []
for
iin
xrange(0,5):- time.sleep(0.1)
- thread = worker()
- thread.start()
- tsk.append(thread)
for
ttin
tsk:
- tt.join()
print
"This is the end of main thread."
運行結果如下:[python] view plain copy
- # python testjoin.py
- This
is
Thread-3;I sleep 2 second. - This
is
Thread-1;I sleep 4 second. - This
is
Thread-2;I sleep 7 second. - This
is
Thread-4;I sleep 7 second. - This
is
Thread-5;I sleep 7 second. - This
is
the end of main thread.
這裡創建了5個子線程,每個線程隨機等待1-10秒後列印退出;主線程分別等待5個子線程結束。最後結果是先顯示各個子線程,再顯示主進程的結果。
2. 如果使用的setDaemon函數,則與join相反,主進程結束的時候不會等待子線程。
setDaemon函數使用實例:
[python] view plain copy
import
timeimport
randomimport
threadingclass
worker(threading.Thread):def
__init__(self):- threading.Thread.__init__(self)
def
run(self):- t = random.randint(1,10)
- time.sleep(t)
print
"This is " + self.getName() + ";I sleep %d second."%(t)- tsk = []
for
i
in
xrange(0,5):- time.sleep(0.1)
- thread = worker()
- thread.setDaemon(True)
- thread.start()
- tsk.append(thread)
print
"This is the end of main thread."
這裡設置主進程為守護進程,當主進程結束的時候,子線程被中止
運行結果如下:
[python] view plain copy
- #python testsetDaemon.py
- This
is
the end of main thread.
3、如果沒有使用join和setDaemon函數,則主進程在創建子線程後,直接運行後面的代碼,主程序一直掛起,直到子線程結束才能結束。
[python] view plain copy
import
timeimport
random
import
threadingclass
worker(threading.Thread):def
__init__(self):- threading.Thread.__init__(self)
def
run(self):- t = random.randint(1,10)
- time.sleep(t)
print
"This is " + self.getName() + ";I sleep %d second."%(t)- tsk = []
for
iin
xrange(0,5):- time.sleep(0.1)
- thread = worker()
- thread.start()
- tsk.append(thread)
print
"This is the end of main thread."
運行結果如下:[python] view plain copy
- # python testthread.py
- This
is
the end of main thread.
- This
is
Thread-4;I sleep 1 second. - This
is
Thread-3;I sleep 7 second. - This
is
Thread-5;I sleep 7 second. - This
is
Thread-1;I sleep 10 second. - This
is
Thread-2;I sleep 10 second.


※淺談WKWebView使用、JS的交互
※python解包和壓包
TAG:程序員小新人學習 |