【发布时间】:2014-11-10 11:53:58
【问题描述】:
我开始研究在 Python 中创建线程。我首先进行了一些理论搜索以了解线程在 Python 中的工作原理。我还继续阅读了 Python 中 Queue 的使用以及它如何帮助解决琐碎的线程问题。我能够理解每个单独的代码。然后我遇到了以下教程:
http://www.ibm.com/developerworks/aix/library/au-threadingpython/
它展示了 Python 中 Thread 和 Queue 的相关性,以及它如何在某些情况下加快执行过程。
我很难理解代码的某些区域
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(5):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
#populate queue with data
for host in hosts:
queue.put(host)
#wait on the queue until everything has been processed
queue.join()
main()
print "Elapsed Time: %s" % (time.time() - start)
在第一个 for 循环中,创建了多个线程并将一个队列实例传递给它。但据我了解,目前队列是空的。
在下一个for循环中
for host in hosts:
主机值被推入队列。现在这个队列数据是如何分配给线程的?
最后,queue.join() 与这个程序有什么关系?
【问题讨论】:
标签: python python-2.7 queue python-multithreading