1. 多線程與停等
一直寫著 JS,所以覺得,如果你在 Python 用一個 threading.Timer 的話,就像 JS的 setTimeout 其余東西都是會繼續(xù)運(yùn)行,而不是會等這個 threading.Timer 運(yùn)行完之后才繼續(xù)進(jìn)行。
但結(jié)果卻是,他其實是放進(jìn)同一個線程,等一個 threading.Timer 完成之后再完成第二個 threading.Timer ,你必須新建一個線程。
就是所說的異步與同步之迷惘。
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)建線程時傳入?yún)?shù)--args參數(shù))
python threading.enumerate()查看線程數(shù)量(多線程二)
python線程數(shù)量與線程池添加鏈接描述
3. 實驗
實驗的函數(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 實驗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
明顯看出,其實線程還是只有一個,只有當(dāng)其中一個線程完全完成了自己的任務(wù) ( TestThreading(0) )后才會調(diào)用下一個任務(wù) ( TestThreading(100) )。
3.2 實驗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),所以我覺得有時候,我真的不想編程,我寧愿做一個自由自在的人,認(rèn)真的活著。
了解語言之間的差別,才是認(rèn)真的事。
5. 為什么我會找到這個問題?
其實我本來是不知道的,但我在做爬蟲的時候發(fā)現(xiàn),執(zhí)行完一次之后,為什么幾個小時也不重新開始爬新的頁面?
因為我是好像 NodeJS 那樣設(shè)定時間的,之前在 Django 也是直接用 threading.Timer 的,為什么會產(chǎn)生等待那么長時間才執(zhí)行下一次程序 ( 我也不想細(xì)看 Django 的線程是怎么做的了 ) 呢。答案就在這里,我討厭異步。