什么是python中的导入锁?

2024-06-08 19:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读“信号量小书”,在书中他有一些代码可以让python使用与他在书中使用的类似的语法。但是,当我尝试导入他的代码时,它会给出以下错误。

from threading_cleanup import *
RuntimeError: not holding the import lock

我知道这和监视程序的函数代码有关,因为如果我把它注释掉,错误就会消失,那里的代码就会产生错误,这样我就可以用键盘中断来结束程序。

有什么方法可以修正这个错误吗?

螺纹清理.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()

Tags: 代码importself程序childtargetsignalos