7

It seems that IDLE (part of the standard Python Windows install) will not execute multithreaded programs correctly without nasty hangs or bugout crashes. Does anyone know of a way to fix this?

The following program will always hang in IDLE but complete normally when executed with the Python interpreter directly:

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!"

sample output:

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!

output when using IDLE "Run Module" function always hangs indefinitely at around the time the line reading 23 or 24 shows up on my machine.

4

3 回答 3

2
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 与需要记录的空闲差异的列表中。

于 2015-03-29T22:53:30.250 回答
0

IDLE 在线程方面存在一些已知问题。我不知道为什么它是一个问题的细节,因为我尽我最大的努力远离 IDLE,但我知道它是。我强烈建议你去获取 IronPython 和 Visual Studio 的 Python 工具。VS 的调试工具绝对无与伦比,尤其是考虑到庞大的附加组件库。

于 2012-08-23T15:58:54.540 回答
0

AFAIK 在 IDLE 中运行线程代码时这是一个废话。IDLE 大量使用 GIL,因此竞争条件和死锁很常见。不幸的是,我在线程方面不够精通,无法提供关于使这个线程安全的见解,而不是显而易见的。

于 2010-07-01T00:39:02.170 回答