2012-12-05 112 views
1

我在阅读一篇关于使用队列的Python多线程的文章,并且有一个基本问题。使用队列的Python多线程

基于print stmt,5个线程按预期启动。那么,队列是如何工作的?

1.线程是最初启动的,当队列填充项时是否重新启动并开始处理该项? 2.如果我们使用队列系统和线程处理队列中的每个项目,那么性能有何提高?它与串行处理不相似,即: 1除以1.

import Queue 
import threading 
import urllib2 
import datetime 
import time 

hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com", 
"http://ibm.com", "http://apple.com"] 

queue = Queue.Queue() 

class ThreadUrl(threading.Thread): 

    def __init__(self, queue): 
    threading.Thread.__init__(self) 
    print 'threads are created' 
    self.queue = queue 

    def run(self): 
    while True: 
     #grabs host from queue 
     print 'thread startting to run' 
     now = datetime.datetime.now() 

     host = self.queue.get() 

     #grabs urls of hosts and prints first 1024 bytes of page 
     url = urllib2.urlopen(host) 
     print 'host=%s ,threadname=%s' % (host,self.getName()) 
     print url.read(20) 

     #signals to queue job is done 
     self.queue.task_done() 

start = time.time() 
if __name__ == '__main__': 

    #spawn a pool of threads, and pass them queue instance 
    print 'program start' 
    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() 


    print "Elapsed Time: %s" % (time.time() - start) 

回答

1

队列与列表容器类似,但具有内部锁定以使其成为线程安全的数据通信方式。

当你开始你的所有线程时会发生什么,它们都会在self.queue.get()呼叫上阻塞,等待从队列中拉出一个项目。从主线程将项目放入队列时,其中一个线程将被解锁并接收项目。然后它可以继续处理它直到完成并返回到阻塞状态。

您的所有线程都可以并发运行,因为它们都能够从队列中接收项目。这是你会看到你的表现有所提高的地方。如果urlopenread在一个线程中花费时间并且它正在IO上等待,这意味着另一个线程可以工作。队列对象作业只是简单地管理锁定访问,并将项目弹出给调用者。