- 论坛徽章:
- 0
|
在IBM网站里找到了一个Python 线程池的例子。
我在执行这个例子,程序却挂起了。哪位大侠能帮忙看看到底是怎么回事吗?
import Queue
import threading
import urllib2
import time
hosts = ["http://www.sina.com.cn/", "http://www.163.com/", "http://www.sohu.com/","http://ibm.com.cn", "http://apple.com.cn"]
queue =Queue.Queue(0)
class ThreadUrl(threading.Thread):
#threaded url Grab
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue =queue
def run(self):
while True:
host =self.queue.get() #从队列queue取出web地址
url =urllib2.urlopen(host)
print url.read(1024) #打印每个web页面前1024个字节
#signals to queue job is done
self.queue.task_done()
start =time.time()
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:
print host
queue.put(host)
#wait on the queue until everything has been processed
queue.join()
main()
print "Elapsed Time: %s" % (time.time() -start)
每次执行时,5个线程都创建了,但每个现在在执行到 run()的红色代码处时停止了
搞不明白了 |
|