首页 > 解决方案 > 如何创建一个用于缓慢记录的线程,以便主要作业可以继续运行(在 python 中)?

问题描述

我的主要工作包括大量计算以及记录许多 IO 操作。我不太关心记录的速度或顺序。我想要的是一个日志收集器,它可以获取我想要登录新线程的上下文,以便我的主脚本可以继续运行而不会被阻塞。

我尝试的代码如下:

import threading
from loguru import logger
from collections import deque
import time

class ThreadLogger:

    def __init__(self):
        self.thread = threading.Thread(target=self.run, daemon=True)
        self.log_queue = deque()
        self.thread.start()
        self.run()

    def run(self):
    # I also have tried while True:
        while self.log_queue:
            log_func, context = self.log_queue.popleft()
            log_func(*context)

    def addLog(self, log_func, context):
        self.log_queue.append([log_func, context])



thlogger = ThreadLogger()
for i in range(20):
    # add log here with new thread so that won't affect main jobs
    thlogger.addLog(logger.debug, (f'hi {i}',))
    # main jobs here (I want to do some real shit here with heavy calculation)

上面的代码并没有像我预期的那样工作。

它无法自行检测何时消化队列

另外,如果我使用“while True:”,它只会阻塞队列,队列永远不会变长。

我能想到的所有其他技术并没有真正在一个新的单线程上做

任何建议我将不胜感激!

标签: pythonmultithreadingasynchronouslogging

解决方案


删除调用self.run(),因为您已经启动了一个线程来运行该方法。正是这个调用阻塞了你的程序。它导致主线程被阻塞在空队列上。

    def __init__(self):
        self.thread = threading.Thread(target=self.run, daemon=True)
        self.log_queue = deque()
        self.thread.start()
        #self.run() # remove

一旦你这样做了,那么你可以更改while self.log_queue:while True:


推荐阅读