Python:在while循环中使用join()的线程
我希望我的while循环对它在for循环中创建的所有线程最多阻塞5秒。但是,以下代码将被线程逐个阻塞。我如何实现我的目标?谢谢Python:在while循环中使用join()的线程,python,join,while-loop,block,python-multithreading,Python,Join,While Loop,Block,Python Multithreading,我希望我的while循环对它在for循环中创建的所有线程最多阻塞5秒。但是,以下代码将被线程逐个阻塞。我如何实现我的目标?谢谢 threads = [] while True: for 3: newThread = threading.Thread(..) threads.append(newThread) newThread.start() newThread.join(5) 要做的一件事是启动所有线程,然后迭代数组并加
threads = []
while True:
for 3:
newThread = threading.Thread(..)
threads.append(newThread)
newThread.start()
newThread.join(5)
要做的一件事是启动所有线程,然后迭代数组并加入。但我想,这仍然需要等待总共5*个线程计数秒。或者,您可以创建一个额外的线程,它只是无限期地等待您的线程。然后在主线程中,您可以等待额外线程5秒钟。您是否尝试每5秒钟生成一个线程,除非已经运行的线程之一结束,您希望更快生成一个新线程?如果是这样,您可以使用
threading.Event
在工作线程结束时发出信号,并使用Event.wait(timeout)
最多阻止事件5秒:
import threading
import time
import logging
logger=logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s: %(message)s',
datefmt='%H:%M:%S')
def foo_event(n,e):
time.sleep(n)
name=threading.current_thread().name
logger.info('{n}: setting event'.format(n=name))
e.set()
def main():
e=threading.Event()
threads=[]
N=5
for i in range(3):
t=threading.Thread(target=foo_event,args=(N+1,e,),name='worker-{i}'.format(i=i))
threads.append(t)
t.daemon=True
t.start()
logger.info('entering wait')
e.wait(N)
logger.info('exit wait')
e.clear()
main()
屈服
05:06:34: entering wait
05:06:39: exit wait <-- Wait 5 seconds
05:06:39: entering wait
05:06:40: worker-0: setting event
05:06:40: exit wait <-- Wait <5 seconds
05:06:40: entering wait
05:06:45: worker-1: setting event
05:06:45: exit wait <-- Wait 5 seconds
05:06:34:进入等待
05:06:39:退出等待您需要使用条件变量(threading.condition
在Python中)。它允许等待谓词变为true。在您的例子中,谓词是所有线程都已完成工作或超时
。下面是创建10个线程并等待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)
导入线程
导入时间
导入日志记录
logging.basicConfig(
格式='%(线程名称)s:%(消息)s',
级别=logging.DEBUG,
)
线程数=10
超时=5
def休眠_线程(延迟,条件):
debug(“嗨,我要延迟%d秒。”%delay)
时间。睡眠(延迟)
debug(“我睡了%d秒。”%delay)
条件获得
debug(“调用notify()”)
条件通知
条件释放()
def创建睡眠线程(延迟,条件):
返回threading.Thread(目标=休眠线程,
args=(延迟,秒))
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
cond=threading.Condition(threading.Lock())
条件获得
工作线程计数器=线程数
对于xrange中的i(线程数):
t=创建线程(i,cond)
t、 开始()
开始时间=time.time()
工作时,计数器>0且(time.time()-开始时间<超时):
等等
工作计数器-=1
logging.debug(“%d个工人仍在工作”,正在工作\u计数器)
条件释放()
logging.debug('完成等待线程(%d个工作线程仍在工作)',
工作人员(柜台)
有关更多信息,请访问。您正在搜索的是Windows中的WaitForMultipleObjects
的pthread模拟。在互联网上找到解决方案可能会有帮助,越快越好。按照您的方法,worker-1必须等待worker-0,对吗?但那不是我想要的。我希望这五条线尽快完成。谢谢你,这就是我需要的!!