python - 需要 while True :

标签 python

我不明白为什么下面的例子需要“while True:”

  import os
  import sys
  import subprocess
  import time
  from threading import Thread
  from Queue import Queue

  def worker():
     while True:
          item = q.get()
          do_work(item)
          q.task_done()

  def do_work(item):
      time.sleep(item)
      print item


  q = Queue()
  for i in range(2):
       t = Thread(target=worker)
       t.daemon = True
       t.start()

  source = [2,3,1,4,5]

  for item in source:
      q.put(item)

  q.join()

最佳答案

否则工作线程会在队列中的第一个作业处理完后立即退出。无限循环确保工作线程在完成后从队列中检索新作业。

更新:总结对我(不可否认的仓促)回答的评论:工作线程是守护进程(由 t.daemon = True 确保),这意味着它当 Python 解释器中只剩下守护线程时将自动终止(给出更详细的解释 here )。另外值得一提的是,worker操作的队列的get方法在队列为空时阻塞线程,让其他线程运行,而worker在等待队列中出现更多作业.

关于python - 需要 while True :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416127/

相关文章:

python - 使用 sleep() 时 Python 运动中的代码不流畅

python - Qt:按钮上没有边框,使其不可点击?

python - 选择字符\x02 和\x0b 之间的子字符串

Python 列表帮助,列表中没有重复项

Python OSC,查询/关闭事件线程

python - Tensorflow `tf.layers.batch_normalization` 没有向 `tf.GraphKeys.UPDATE_OPS` 添加更新操作

python - scrapy list return:如何处理/提取列表的每个元素?

python - Selenium 导致Windows错误

python - 在python中将二维数组转换为彩色图像

python - 正则表达式: Removing this [##### : #####] from a string