Skip to main content
 首页 » 编程设计

python之什么是 python 中的导入锁

2025年05月04日24虾米哥

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

from threading_cleanup import * 
RuntimeError: not holding the import lock 

我知道它与 watcher 函数代码有关,因为如果我将其注释掉,错误就会消失,那里的代码会产生错误,因此我可以使用 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() 

请您参考如下方法:

本题题目问的是import lock是什么

导入锁是 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 

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