Python IDLE 与多线程兼容吗?

2023-11-25

看起来 IDLE(标准 Python Windows 安装的一部分)不会正确执行多线程程序,除非出现严重的挂起或 bugout 崩溃。有谁知道解决这个问题的方法吗?

以下程序将始终挂在 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 差异列表中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python IDLE 与多线程兼容吗? 的相关文章

随机推荐