Python IDLE 与多线程兼容吗?
看起来,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行出现时无限期地卡住。
3 个回答
0
IDLE在处理多线程时有一些已知的问题。我对这些问题的具体原因了解得不多,因为我尽量避免使用IDLE,但我知道确实存在这些问题。我强烈建议你去下载IronPython和Visual Studio的Python工具。Visual Studio的调试工具非常出色,尤其是它有很多额外的插件可以使用。
3
import threading
print(threading.activeCount())
在命令行运行时会打印1,而在Idle中运行时会打印2。所以你的循环
while threading.activeCount() > 1:
time.sleep(1)
pl( time.time() )
在控制台会结束,但在Idle中会一直运行下去。
要解决这个代码中的问题,可以在导入之后加上类似的内容
initial_threads = threading.activeCount()
并把循环的开头改成
while threading.activeCount() > initial_threads:
这样改完后,代码会运行30次,然后显示'全部完成!'。我把这个添加到了我需要记录的控制台Python和Idle之间的差异列表中。
0
据我所知,在IDLE中运行多线程代码就像掷骰子一样,结果很不确定。IDLE在使用全局解释器锁(GIL)时非常频繁,所以出现竞争条件和死锁的情况很常见。可惜的是,我对多线程的了解不够深入,无法提供更多关于如何让这个线程安全的建议,除了那些显而易见的做法。