【发布时间】:2011-01-21 00:47:06
【问题描述】:
我正在阅读“信号量小书”,其中他有一些代码可以使 python 使用与他在书中使用的语法相似的语法。但是,当我尝试导入他的代码时,它给了我以下错误。
from threading_cleanup import *
RuntimeError: not holding the import lock
我知道它与观察程序函数代码有关,因为如果我将其注释掉,错误就会消失,那里的代码会生成它,因此我可以使用 KeyboardInterrupt 来结束程序。
有什么办法可以解决这个错误吗?
threading_cleanup.py
import threading
import time
import os
import signal
import sys
__all__ = ['Thread', 'Semaphore', 'watcher']
class Thread(threading.Thread):
def __init__(self, target, *args):
threading.Thread.__init__(self, target=target, args=args)
self.start()
class Semaphore(threading._Semaphore):
wait = threading._Semaphore.acquire
def signal(self, n=1):
for _ in range(n): self.release()
def value(self):
return self._Semaphore__value
def watcher():
child = os.fork()
if child == 0: return
try:
os.wait()
except KeyboardInterrupt:
print 'KeyboardInterrupt'
os.kill(child, signal.SIGKILL)
sys.exit()
watcher()
【问题讨论】:
-
你不能用
try-except KeyboardInterrupt包裹你的程序来完成它吗?为什么要为此创建单独的流程? -
作为参考,我删除的答案作为评论:对我来说,使用 IPython 时会发生此错误,但使用 vanilla Python 解释器时不会发生此错误。但是 Zach 没有使用 IPython,所以这不是他的原因。
-
@ulidtko 我认为这样您就不必将其放在每个程序的末尾。由于这是书上的,大部分程序都是小程序,所以我想用一个导入解决问题会更容易。
-
@Sven Marnach 我在 mac os x 上使用了 32 位版本的 python 2.7。在默认安装的 python 2.6 中,代码运行良好,所以我猜它只是我的解释器。
-
@Zach:非常奇怪的问题。我认为值得在 Python 开发者邮件列表中询问。
标签: python multithreading