python - 如何创建一个用于缓慢记录的线程,以便主要作业可以继续运行(在 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:”,它只会阻塞队列,队列永远不会变长。
我能想到的所有其他技术并没有真正在一个新的单线程上做
任何建议我将不胜感激!
解决方案
删除调用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:
推荐阅读
- c# - 将双精度 0,10 转换为字符串并在最后一位数字后保留 0 或按原样将双精度转换为字符串
- javascript - Tempus Dominus 无法在动态输入中设置 minDate 或 maxDate
- powerbi - 一个日期轴 dax 上的两年比较
- ruby-on-rails - 错误:找不到要导入的文件或无法读取:引导电子邮件
- tensorflow - 在 Tensorflow 中计算损失函数的 Hessian
- laravel - 在嵌套表单上使用 required_without
- python - 减少python应用程序中的DNS查询
- docker - gitlab CI/CD:缓存 docker 镜像构建
- javascript - Property does not exist on type String error
- javascript - Promise.all 产生“油门队列超过最大容量”