python - python中的导入锁是什么?

标签 python multithreading

我正在阅读“The Little Book of Semaphores”,其中他有一些代码可以使 python 使用与他在书中使用的语法类似的语法。但是,当我尝试导入他的代码时,出现以下错误。

from threading_cleanup import *
RuntimeError: not holding the import lock

我知道它与观察程序函数代码有关,因为如果我将其注释掉,错误就会消失,那里的代码会使它消失,这样我就可以使用键盘中断来结束程序。

有什么办法可以修复这个错误吗?

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()

最佳答案

这个问题的标题询问导入锁是什么。

导入锁是 Python 的 import 实现的一部分,如果违反这些模糊的限制,它会使程序失败:

https://docs.python.org/2/library/threading.html#importing-in-threaded-code

在您的情况下,因为您直接在模块中调用 watcher() ,所以它无法启动线程,除非该模块恰好是主模块。这是一个例子:

python2.7 - import silently locks up the thread

不过,您的示例似乎有点不同,因为它涉及流程。如果我将您的 threading_cleanup.py 减少为:

import os
def watcher():
    child = os.fork()
watcher()

我仍然遇到同样的错误:

  File "main.py", line 1, in <module>
    import threading_cleanup.py
RuntimeError: not holding the import lock

天哪,这不是导入锁。除了错误消息说它是导入锁之外,现在不是吗?听起来像是错误消息文本中的错误。

关于python - python中的导入锁是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4754319/

相关文章:

具有多个 'if' s的python列表理解

Java线程yield方法查询

c++ - 通过两个线程递增的全局变量的最终值

在 dict 中移动所有键的 Pythonic 方法

python - "AttributeError: ' 描述 ' object has no attribute ' co_button '"与 tkinter

php - 处理高负载文件 I/O 的最佳实践是什么?

c# - 如何正确使用 ConcurrentQueue 中的 block

android - Android 开发中的 UI 访问

python - 如何查字典?

python - 在 Hadoop UDF 输出中保留列数据类型(流)