import threading
import Queue
import urllib2
import time
class ThreadURL(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
host = self.queue.get()
sock = urllib2.urlopen(host)
data = sock.read()
self.queue.task_done()
hosts = ['http://www.google.com', 'http://www.yahoo.com', 'http://www.facebook.com', 'http://stackoverflow.com']
start = time.time()
def main():
queue = Queue.Queue()
for i in range(len(hosts)):
t = ThreadURL(queue)
t.start()
for host in hosts:
queue.put(host)
queue.join()
if __name__ == '__main__':
main()
print 'Elapsed time: {0}'.format(time.time() - start)
我一直在试着弄清楚如何执行线程,在一些教程之后,我想出了上面的方法。在
它应该做的是:
我首先想知道的是,我做得对吗?这是处理线程的最佳方法吗?在
其次,我的程序无法退出。它打印出Elapsed time
行,然后挂在那里。我必须杀死我的终端才能让它消失。我想这是因为我错误地使用了queue.join()
?在
你的代码看起来很好,很干净。在
应用程序仍然“挂起”的原因是工作线程仍在运行,等待主应用程序将某些内容放入队列,即使主线程已完成。在
解决此问题的最简单方法是在调用start之前执行
t.daemon = True
,将线程标记为守护进程。这样,线程就不会阻止程序停止。在看起来不错。yann关于守护进程的建议是对的。这会解决你的问题。我唯一的问题是为什么要排队?您没有进行任何跨线程通信,因此似乎可以将主机信息作为一个参数发送到ThreadURL init()并删除队列。在
没什么问题,只是想知道。在
有一件事,在线程运行函数while True循环中,如果发生异常,则可能不会调用task\u done(),但get()已经被调用。因此队列.join()可能永远不会结束。在
相关问题 更多 >
编程相关推荐