Python:在while循环中使用join()的线程
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:在while循环中使用join()的线程,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1436字,纯文字阅读大概需要3分钟。
内容图文
![Python:在while循环中使用join()的线程](/upload/InfoBanner/zyjiaocheng/674/5d410271378e4b479e0e841392db7a24.jpg)
我希望我的while循环在for循环中创建的所有线程最多阻塞5秒.但是,以下代码将逐个线程阻塞线程.我该如何实现自己的目标?谢谢.
threads = []
while True:
for 3:
newThread = threading.Thread(..)
threads.append(newThread)
newThread.start()
newThread.join(5)
解决方法:
您需要使用条件变量(Python中的threading.Condition).它允许等待谓词变为真.在您的情况下,谓词是所有线程均已完成工作或超时.这是创建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)
有关详细信息,请致电comp.programming.threads FAQ.
内容总结
以上是互联网集市为您收集整理的Python:在while循环中使用join()的线程全部内容,希望文章能够帮你解决Python:在while循环中使用join()的线程所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。