![](/img/trans.png)
[英]is there a compatible TCL environment variable for cygwin and python idle
[英]Python IDLE compatible with multithreading?
似乎IDLE(標准Python Windows安裝的一部分)將不會正確執行多線程程序而不會出現令人討厭的掛起或錯誤崩潰。 有誰知道解決這個問題的方法?
以下程序將始終掛在IDLE中,但在使用Python解釋器直接執行時正常完成:
import threading, time
printLock = threading.Lock()
def pl(s):
printLock.acquire()
print s
printLock.release()
class myThread( threading.Thread ):
def run(self):
i = 0
for i in range(0,30):
pl(i)
time.sleep(0.1)
t = myThread()
t.start()
while threading.activeCount() > 1:
time.sleep(1)
pl( time.time() )
print "all done!"
樣本輸出:
U:\dev\py\multithreadtest>python mt.py
0
1
2
3
4
5
6
7
8
9
1277935368.84
10
11
12
13
14
15
16
17
18
19
1277935369.84
20
21
22
23
24
25
26
27
28
29
1277935370.84
1277935371.84
all done!
使用IDLE時的輸出“運行模塊”功能始終在我的機器上顯示23或24行讀數時無限期掛起。
import threading
print(threading.activeCount())
在命令行運行時打印1,從空閑運行時打印2。 所以你的循環
while threading.activeCount() > 1:
time.sleep(1)
pl( time.time() )
將在控制台終止,但永遠在空閑狀態下繼續。
要解決已發布代碼中的問題,請添加類似的內容
initial_threads = threading.activeCount()
導入后,將循環標題更改為
while threading.activeCount() > initial_threads:
通過此更改,代碼將運行30個周期並以“全部完成!”停止。 我已將此添加到我需要記錄的控制台Python與空閑差異列表中。
在涉及線程時,IDLE有一些已知問題。 我不知道為什么這是一個問題的詳細信息,因為我盡我所能遠離IDLE,但我知道它是。 我強烈建議你去Visual Studio獲取IronPython和Python工具。 VS的調試工具絕對無與倫比,特別是考慮到龐大的附加庫。
在IDLE中運行線程代碼時,AFAIK是一個crapshoot。 IDLE大量使用GIL,因此競爭條件和死鎖很常見。 不幸的是,我並沒有足夠精通線程來提供有關使這個線程安全的見解,超越顯而易見的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.