1. 多線程與停等
一直寫著 JS
帆调,所以覺得虹钮,如果你在 Python
用一個(gè) threading.Timer
的話喻鳄,就像 JS
的 setTimeout
其余東西都是會(huì)繼續(xù)運(yùn)行陋葡,而不是會(huì)等這個(gè) threading.Timer
運(yùn)行完之后才繼續(xù)進(jìn)行奈附。
但結(jié)果卻是腮出,他其實(shí)是放進(jìn)同一個(gè)線程
怀偷,等一個(gè) threading.Timer
完成之后再完成第二個(gè) threading.Timer
宠叼,你必須新建一個(gè)線程
鄙皇。
就是所說的異步
與同步
之迷惘芜赌。
graph LR
NodeJS
A[主程序] -. setTimeout 1 .-> B((執(zhí)行程序 1))
B -- setTimeout 1--> B
A[主程序] -. setTimeout 2 .-> D((執(zhí)行程序 2))
D -- setTimeout 2--> D
graph LR
Python
A[主程序] -. threading.Timer 1.-> B((執(zhí)行程序 1))
B -- threading.Timer 1 --> B
B --需要等執(zhí)行程序 1完成 -->D
A[主程序] -. threading.Timer 2 .-> D((執(zhí)行程序 2))
D -- threading.Timer 2--> D
2. 參考文章
Python多任務(wù)(利用threading創(chuàng)建線程時(shí)傳入?yún)?shù)--args參數(shù))
python threading.enumerate()查看線程數(shù)量(多線程二)
python線程數(shù)量與線程池添加鏈接描述
3. 實(shí)驗(yàn)
實(shí)驗(yàn)的函數(shù)為:
def TestThreading(t):
time.sleep(6)
print('Now It\'s :'+ str(t))
# print(' Now enumerate is :'+str(len(threading.enumerate())))
print(' Now activeCount is :'+str(len(threading.enumerate())))
TT=threading.Timer(2, TestThreading(t+1))
TT.start()
3.1 實(shí)驗(yàn)1
調(diào)用函數(shù)為:
threading.Timer(2, TestThreading(0)).start()
threading.Timer(2, TestThreading(100)).start()
threading.Timer(2, TestThreading(200)).start()
threading.Timer(2, TestThreading(300)).start()
輸出為:
Now It's :0
Now activeCount is :1
Now It's :1
Now activeCount is :1
Now It's :2
Now activeCount is :1
Now It's :3
Now activeCount is :1
Now It's :4
Now activeCount is :1
Now It's :5
Now activeCount is :1
明顯看出,其實(shí)線程
還是只有一個(gè)
伴逸,只有當(dāng)其中一個(gè)線程
完全完成了自己的任務(wù) ( TestThreading(0)
)后才會(huì)調(diào)用下一個(gè)任務(wù) ( TestThreading(100)
)缠沈。
3.2 實(shí)驗(yàn)2
調(diào)用函數(shù)為:
def Go(t):
TestThreading(t)
threading.Thread(target = Go,args=(0,)).start()
threading.Thread(target = Go,args=(100,)).start()
threading.Thread(target = Go,args=(300,)).start()
輸出為:
Now It's :300
Now It's :100
Now activeCount is :4
Now activeCount is :4
Now It's :0
Now activeCount is :4
Now It's :301
Now activeCount is :4
Now It's :101
Now activeCount is :4
Now It's :1
Now activeCount is :4
Now It's :302
Now activeCount is :4
Now It's :102
Now activeCount is :4
Now It's :2
Now activeCount is :4
Now It's :303
Now activeCount is :4
Now It's :103
Now It's :3
Now activeCount is :4
Now activeCount is :4
Now It's :304
Now activeCount is :4
Now It's :104
Now activeCount is :4
Now It's :4
Now activeCount is :4
Now It's :305
Now activeCount is :4
Now It's :105
Now activeCount is :4
Now It's :5
Now activeCount is :4
4. 我真的討厭異步與同步
不同語言
之間的特性
差別真的差很遠(yuǎn),所以我覺得有時(shí)候错蝴,我真的不想編程洲愤,我寧愿做一個(gè)自由自在的人,認(rèn)真的活著顷锰。
了解語言之間的差別柬赐,才是認(rèn)真的事。
5. 為什么我會(huì)找到這個(gè)問題官紫?
其實(shí)我本來是不知道的肛宋,但我在做爬蟲的時(shí)候發(fā)現(xiàn),執(zhí)行完一次之后束世,為什么幾個(gè)小時(shí)也不重新開始爬新的頁面酝陈?
因?yàn)槲沂呛孟?NodeJS
那樣設(shè)定時(shí)間
的,之前在 Django
也是直接用 threading.Timer
的毁涉,為什么會(huì)產(chǎn)生等待那么長時(shí)間才執(zhí)行下一次程序 ( 我也不想細(xì)看 Django
的線程
是怎么做的了 ) 呢沉帮。答案就在這里,我討厭異步
薪丁。