gpt4 book ai didi

Python:在 while 循环中使用 join() 的线程

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:23 24 4
gpt4 key购买 nike

我希望我的 while 循环为其在 for 循环中创建的所有线程最多阻塞 5 秒。但是,下面的代码会被线程一个一个阻塞。我怎样才能接近我的目标?谢谢。

threads = []
while True:
for 3:
newThread = threading.Thread(..)
threads.append(newThread)
newThread.start()
newThread.join(5)

最佳答案

您需要使用条件变量(Python 中的threading.Condition)。它允许等待谓词变为真。在您的情况下,谓词是 all threads have finished work or time out exceeded。这是创建十个线程并等待它们完成的代码,超时时间为 5 秒。详细日志将帮助您:

import threading
import time
import logging


logging.basicConfig(
format='%(threadName)s:%(message)s',
level=logging.DEBUG,
)


NUM_OF_THREADS = 10
TIMEOUT = 5


def sleeping_thread(delay, cond):
logging.debug("Hi, I'm going to delay by %d sec." % delay)
time.sleep(delay)
logging.debug("I was sleeping for %d sec." % delay)
cond.acquire()
logging.debug("Calling notify().")
cond.notify()
cond.release()


def create_sleeping_thread(delay, cond):
return threading.Thread(target=sleeping_thread,
args=(delay, cond))


if __name__ == '__main__':
cond = threading.Condition(threading.Lock())
cond.acquire()

working_counter = NUM_OF_THREADS
for i in xrange(NUM_OF_THREADS):
t = create_sleeping_thread(i, cond)
t.start()

start_time = time.time()
while working_counter > 0 and (time.time() - start_time < TIMEOUT):
cond.wait()
working_counter -= 1
logging.debug('%d workers still working', working_counter)
cond.release()
logging.debug('Finish waiting for threads (%d workers still working)',
working_counter)

更多信息请访问 comp.programming.threads FAQ .

关于Python:在 while 循环中使用 join() 的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7937755/

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