为什么我的多进程队列似乎不是线程安全的?

4

我正在构建一个看门狗计时器来运行另一个Python程序,如果它无法从任何线程中找到检查,则会关闭整个程序。这样做是为了最终能够控制所需的通信端口。计时器的代码如下:

from multiprocessing import Process, Queue
from time import sleep
from copy import deepcopy

PATH_TO_FILE = r'.\test_program.py'
WATCHDOG_TIMEOUT = 2

class Watchdog:

    def __init__(self, filepath, timeout):
        self.filepath = filepath
        self.timeout = timeout
        self.threadIdQ = Queue()
        self.knownThreads = {}

    def start(self):
        threadIdQ = self.threadIdQ

        process = Process(target = self._executeFile)
        process.start()
        try:
            while True:
                unaccountedThreads = deepcopy(self.knownThreads)

                # Empty queue since last wake. Add new thread IDs to knownThreads, and account for all known thread IDs
                # in queue
                while not threadIdQ.empty():
                    threadId = threadIdQ.get()
                    if threadId in self.knownThreads:
                        unaccountedThreads.pop(threadId, None)
                    else:
                        print('New threadId < {} > discovered'.format(threadId))
                        self.knownThreads[threadId] = False

                # If there is a known thread that is unaccounted for, then it has either hung or crashed.
                # Shut everything down.
                if len(unaccountedThreads) > 0:
                    print('The following threads are unaccounted for:\n')
                    for threadId in unaccountedThreads:
                        print(threadId)
                    print('\nShutting down!!!')
                    break
                else:
                    print('No unaccounted threads...')

                sleep(self.timeout)

        # Account for any exceptions thrown in the watchdog timer itself
        except:
            process.terminate()
            raise

        process.terminate()


    def _executeFile(self):
        with open(self.filepath, 'r') as f:
            exec(f.read(), {'wdQueue' : self.threadIdQ})

if __name__ == '__main__':
    wd = Watchdog(PATH_TO_FILE, WATCHDOG_TIMEOUT)
    wd.start()

我还有一个小程序来测试看门狗功能。
from time import sleep
from threading import Thread
from queue import SimpleQueue

Q_TO_Q_DELAY = 0.013

class QToQ:

    def __init__(self, processQueue, threadQueue):
        self.processQueue = processQueue
        self.threadQueue = threadQueue
        Thread(name='queueToQueue', target=self._run).start()

    def _run(self):
        pQ = self.processQueue
        tQ = self.threadQueue
        while True:
            while not tQ.empty():
                sleep(Q_TO_Q_DELAY)
                pQ.put(tQ.get())

def fastThread(q):
    while True:
        print('Fast thread, checking in!')
        q.put('fastID')
        sleep(0.5)

def slowThread(q):
    while True:
        print('Slow thread, checking in...')
        q.put('slowID')
        sleep(1.5)

def hangThread(q):
    print('Hanging thread, checked in')
    q.put('hangID')
    while True:
        pass

print('Hello! I am a program that spawns threads!\n\n')

threadQ = SimpleQueue()

Thread(name='fastThread', target=fastThread, args=(threadQ,)).start()
Thread(name='slowThread', target=slowThread, args=(threadQ,)).start()
Thread(name='hangThread', target=hangThread, args=(threadQ,)).start()

QToQ(wdQueue, threadQ)

如您所见,我需要将线程放入队列.Queue中,而另一个独立的对象会慢慢将队列.Queue的输出馈送到多进程队列中。如果我直接将线程放入多进程队列中,或者在puts之间没有让QToQ对象休眠,那么多进程队列将会锁定,并且在看门狗方面始终为空。
现在,由于多进程队列应该是线程和进程安全的,我只能假设我在实现中出了问题。我的解决方案似乎有效,但也感觉很麻烦,我觉得我应该修复它。
我使用的是Python 3.7.2,如果有影响,请注意。

我正在使用Python 3.6 (from queue import Queue),但我无法使其失败。我可以直接通过wdQueue发送ID,也可以通过QToQ和队列发送ID,而Watchdog总是能够捕获到hangID并关闭程序。 - quamrana
更新:尽管没有“hangThread”,它总会在某个时候关闭。 - quamrana
你的 except 应该改成 finally - Davis Herring
1个回答

1
我猜测 test_program.py 已经退出。
我将最后几行修改为以下内容:
tq = threadQ
# tq = wdQueue    # option to send messages direct to WD

t1 = Thread(name='fastThread', target=fastThread, args=(tq,))
t2 = Thread(name='slowThread', target=slowThread, args=(tq,))
t3 = Thread(name='hangThread', target=hangThread, args=(tq,))

t1.start()
t2.start()
t3.start()
QToQ(wdQueue, threadQ)

print('Joining with threads...')
t1.join()
t2.join()
t3.join()

print('test_program exit')

join() 的调用意味着测试程序永远不会自行退出,因为没有任何线程退出。

因此,t3 此时会挂起,看门狗程序检测到这一点并检测到未经记录的线程,然后停止测试程序。

如果从上述程序中删除 t3,则其他两个线程将表现良好,看门狗程序将允许测试程序无限期地继续运行。


谢谢!加入线程似乎确实解决了问题,即使我不创建QToQ,而是线程直接写入多进程队列。我仍然很困惑为什么使用QToQ似乎可以解决问题,但我会稍后进行调查;这显然是更好的解决方案。 - Nelson S.
有趣的一点是:我尝试在看门狗计时器循环中放置 process.is_alive() 的检查,但它总是返回 true,即使出现错误时也是如此。然而,似乎问题仍然是进程退出,因为像 while True: pass 这样简单的东西也似乎可以解决它。 - Nelson S.
你应该尽量避免繁忙等待,例如 while True:pass,而是使用合理的阻塞方式,如 t1.join()。这可以减少服务器的 CPU 负载。 - quamrana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接