gpt4 book ai didi

Python - 线程和 While True 循环

转载 作者:太空狗 更新时间:2023-10-29 18:28:29 24 4
gpt4 key购买 nike

我有一个将行附加到 self.output 的线程和一个运行直到 self.done 为真(或达到最大执行时间)的循环。

除了使用不断检查是否已完成的 while 循环之外,是否有更有效的方法来执行此操作。 while 循环导致 CPU 在运行时达到 100%。

time.clock()
while True:

if len(self.output):
yield self.output.pop(0)

elif self.done or 15 < time.clock():
if 15 < time.clock():
yield "Maximum Execution Time Exceeded %s seconds" % time.clock()
break

最佳答案

您的线程是否附加到此处的 self.output,而您的主要任务正在消耗它们?如果是这样,这是为Queue.Queue量身定做的工作。 .你的代码应该是这样的:

import Queue

# Initialise queue as:
queue = Queue.Queue()
Finished = object() # Unique marker the producer will put in the queue when finished

# Consumer:
try:
while True:
next_item = self.queue.get(timeout=15)
if next_item is Finished: break
yield next_item

except Queue.Empty:
print "Timeout exceeded"

您的生产者线程使用queue.put(item)将项目添加到队列中

[编辑] 原始代码在检查 self.done 时存在竞争问题(例如,在设置标志之前,多个项目可能会附加到队列中,导致代码在第一)。根据 ΤZΩΤZΙΟΥ 的建议进行了更新 - 生产者线程应该改为将特殊标记(已完成)附加到队列以指示它已完成。

注意:如果您有多个生产者线程,您将需要一种更通用的方法来检测它们何时全部完成。您可以使用相同的策略来完成此操作 - 每个线程都有一个 Finished 标记,并且消费者在看到 num_threads 个标记时终止。

关于Python - 线程和 While True 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/808746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com