Python IDLE与多线程兼容吗? [英] Python IDLE compatible with multithreading?

查看:117
本文介绍了Python IDLE与多线程兼容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有令人讨厌的挂起或bugout崩溃的情况下,IDLE(标准Python Windows安装的一部分)似乎无法正确执行多线程程序.有人知道解决此问题的方法吗?

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?

以下程序将始终挂在IDLE中,但直接用Python解释器执行时正常完成:

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

示例输出:

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的时间.

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.

推荐答案

AFAIK在IDLE中运行线程代码时,它是一种解决方法. IDLE自由地使用GIL,因此竞争条件和死锁很常见.不幸的是,我并不精通线程技术,无法提供使线程安全的见解.

AFAIK it's a crapshoot when running threaded code in IDLE. IDLE uses the GIL liberally so race conditions and deadlocks are common. Unfortunately, I am not well versed enough in threading to offer insight on making this thread-safe, beyond the obvious.

这篇关于Python IDLE与多线程兼容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆