多線程編程中的join函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# coding: utf-8
# 測試多線程中join的功能
import
threading, time
def
doWaiting():
print
'start waiting1: '
+
time.strftime(
'%H:%M:%S'
)
+
"\n"
time.sleep(
3
)
print
'stop waiting1: '
+
time.strftime(
'%H:%M:%S'
)
+
"\n"
def
doWaiting1():
print
'start waiting2: '
+
time.strftime(
'%H:%M:%S'
)
+
"\n"
time.sleep(
8
)
print
'stop waiting2: '
, time.strftime(
'%H:%M:%S'
)
+
"\n"
tsk
=
[]
thread1
=
threading.Thread(target
=
doWaiting)
thread1.start()
tsk.append(thread1)
thread2
=
threading.Thread(target
=
doWaiting1)
thread2.start()
tsk.append(thread2)
print
'start join: '
+
time.strftime(
'%H:%M:%S'
)
+
"\n"
for
tt
in
tsk:
tt.join()
print
'end join: '
+
time.strftime(
'%H:%M:%S'
)
+
"\n"
|
Join的作用是眾所周知的,阻塞進程直到線程執行完畢
這個小程序使用了兩個線程thread1和thread2,線程執行的動作分別是doWaiting()和doWaiting1(),函數體就是打印「開始」+休眠3秒+打印「結束」,分別附加上時間用來查看程序執行的過程。后面用start()方法同步開始執行兩個線程。然后開始循環調用兩個線程的join()方法,在此之前和之后都會用print函數做好開始結束的標記。我們主要觀察for tt in tsk: tt.join()。
join()不帶參數的情況下,執行如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
start waiting1:
22
:
54
:
09
start waiting2:
22
:
54
:
09
start join:
22
:
54
:
09
stop waiting1:
22
:
54
:
12
stop waiting2:
22
:
54
:
17
end join:
22
:
54
:
17
Process finished with exit code
0
|
可以看到,兩個線程並行執行,進程1在3s后結束,進程2在8s后結束,然后回到主進程,執行打印「end join」。
下面把參數設置成超時2s,即tt.join(2),執行如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
start waiting1:
22
:
54
:
57
start waiting2:
22
:
54
:
57
start join:
22
:
54
:
57
stop waiting1:
22
:
55
:
00
end join:
22
:
55
:
01
stop waiting2:
22
:
55
:
05
Process finished with exit code
0
|
兩個線程開始並發執行,然后執行線程1的join(2),等線程1執行2s后就不管它了,執行線程2的join(2),等線程2執行2s后也不管它了(在此過程中線程1執行結束,打印線程1的結束信息),開始執行主進程,打印「end join」。4s之后線程2執行結束。
總結一下:
1.join方法的作用是阻塞主進程(擋住,無法執行join以后的語句),專注執行多線程。
2.多線程多join的情況下,依次執行各線程的join方法,前頭一個結束了才能執行后面一個。
3.無參數,則等待到該線程結束,才開始執行下一個線程的join。
4.設置參數后,則等待該線程這么長時間就不管它了(而該線程並沒有結束)。不管的意思就是可以執行后面的主進程了。
最后附上參數為2時的程序執行流程表,自己畫的orz,這樣看起來更好理解。