需要使用Python线程/队列一些援助 [英] Need some assistance with Python threading/queue

查看:167
本文介绍了需要使用Python线程/队列一些援助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

我一直试图让我的周围如何执行线程头和一些教程后,我想出了上面。

I've been trying to get my head around how to perform Threading and after a few tutorials, I've come up with the above.

什么它应该做的是:


  1. Initialiase队列

  2. 创建我的线程池,然后排队的主机列表

  3. 然后
  4. 我ThreadURL类应该开始工作,一旦一台主机是在队列和阅读网站数据

  5. 程序要完成

我想知道的第一关是什么,我在做正确吗?这是处理线程的最佳方式?

What I want to know first off is, am I doing this correctly? Is this the best way to handle threads?

其次,我的程序无法退出。它打印出经过时间行,然后挂在那儿。我要杀死我的终端为它去了。我假设这是因为我的)不正确的使用的queue.join(

Secondly, my program fails to exit. It prints out the Elapsed time line and then hangs there. I have to kill my terminal for it to go away. I'm assuming this is due to my incorrect use of queue.join() ?

推荐答案

您code看起来不错,是相当干净。

Your code looks fine and is quite clean.

您的应用程序仍然是挂起的原因是,工作线程仍在运行,等待主应用程序把一些在排队,即使你的主线程就完成了。

The reason your application still "hangs" is that the worker threads are still running, waiting for the main application to put something in the queue, even though your main thread is finished.

解决这个问题的最简单方法是通过做标记线程为守护程序, t.daemon = TRUE 之前,您的来电开始。这样,线程不会阻止该程序停止。

The simplest way to fix this is to mark the threads as daemons, by doing t.daemon = True before your call to start. This way, the threads will not block the program stopping.

这篇关于需要使用Python线程/队列一些援助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆