關於python多線程編程中join()和setDaemon()的用法,這兩天我看網上的資料看得頭暈腦漲也沒看懂,干脆就做一個實驗來看看吧。
首先是編寫實驗的基礎代碼,創建一個名為MyThread的 類,然后通過向這個類傳入print_func這個方法,分別創建了兩個子線程:
#!/usr/bin/env python
import threading
import time
class MyThread(threading.Thread): def __init__(self, func, args, name=''): threading.Thread.__init__(self) self.name=name self.func=func self.args=args def run(self): apply(self.func, self.args) def print_func(num): while True: print "I am thread%d" % num time.sleep(1) threads = [] t1 = MyThread(print_func, (1, ), print_func.__name__) threads.append(t1) t2 = MyThread(print_func, (2, ), print_func.__name__) threads.append(t2)
首先來試試setDaemon()的設置,在上面基礎代碼的后面加上以下的代碼:
for t in threads: t.setDaemon(True) t.start() print "ok\n"
程序輸出:
I am thread1
I am thread2
ok
print_func()中的while循環沒有繼續執行下去就退出了,可見由於setDaemon(True)把子線程設置為守護線程,子線程啟動后,父線程也繼續執行下去,當父線程執行完最后一條語句print "ok\n"后,沒有等待子線程,直接就退出了,同時子線程也一同結束。
下面我們把添加的代碼更改如下:
for t in threads: t.start() t.join() print "ok\n"
這個時候程序會輸出:
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
。。。
這樣一直循環下去,可見只有第一個子線程被調用了,第二個子線程,以及父線程都沒有繼續走下去。這里我的理解是:join()的作用是,在子線程完成運行之前,這個子線程的父線程將一直被阻塞。,無法運行下去。在這里父線程沒法繼續執行for循環,所以第二個子線程也就不會出現了。
接下來再修改一下代碼:
for t in threads: t.start() for t in threads: t.join() print "ok\n"
這時程序輸出:
I am thread1
I am thread2
I am thread1
I am thread2
I am thread1
I am thread2
I am thread1
。。。
可見這個時候兩個子線程都在運行了,同樣在兩個子線程完成之前,父線程的print "ok\n"都不會執行。
之前的實驗中,兩個子線程的運行時間是一樣的,那么假如兩個線程耗時不一樣,一個子線程先於另一個子線程完成執行,會發生什么情況呢,於是我增加了一個什么都不干的方法pass_func:
#! /usr/bin/env python #coding=utf-8 import threading import time class MyThread(threading.Thread): def __init__(self, func, args, name=''): threading.Thread.__init__(self) self.name=name self.func=func self.args=args def run(self): apply(self.func, self.args) def print_func(num): while True: print "I am thread%d" % num time.sleep(1) def pass_func(): pass threads = [] t1 = MyThread(print_func, (1, ), print_func.__name__) threads.append(t1) t2 = MyThread(pass_func, (), pass_func.__name__) threads.append(t2) for t in threads: t.start() for t in threads: t.join() print "ok\n"
這段代碼的執行結果是:
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
I am thread1
。。。
可見這時侯,一個子線程的完成不會影響另外一個子線程,父線程仍然一直被阻塞着。
有些時候,還可以單獨對某一個子線程設定join(),以達到特定的效果,例如下面這段代碼片段的用意是,分別設立一個子線程用於接收數據,另外一個子線程用於發送數據,當用戶輸入“quit”時,程序退出:
def send(sck): while True: data = raw_input('>') sck.send(data) if data == "quit": sck.close() break def recieve(sck): while True: data = sck.recv(BUFSIZ) print data, "\n"
threads = [] t1 = threading.Thread(target=send, args = (tcpCliSock, )) threads.append(t1) t2 = threading.Thread(target=recieve, args = (tcpCliSock, )) threads.append(t2) for t in threads: t.start() t1.join()
這段代碼中,把t1,也就是send所對應的子線程添加上join()屬性,讓父線程在send方法對應的子線程結束前一直在阻塞狀態。假如把兩個子線程t1和t2都添加上join()屬性,這會使得send方法收到“quit”命令,退出循環后,由於recieve方法仍然在循環當中,父線程仍然被阻塞着,結果程序無法退出。只對t1添加join()屬性,那么t1結束了,父線程會繼續執行下去,直到執行完最后一條代碼后退出,然后t2也跟着一同結束,達到所有線程都退出的目的,這就是t1.join()這條命令的用意。