Queue.join()不会解除阻止

use*_*055 5 python queue multithreading

我正在尝试编写用于并行抓取网站的Python脚本。我制作了一个原型,使我可以深入到一个深度。

但是,join()似乎没有用,我不知道为什么。

这是我的代码:

from threading import Thread
import Queue
import urllib2
import re
from BeautifulSoup import *
from urlparse import urljoin


def doWork():
    while True:
        try:
            myUrl = q_start.get(False)
        except:
            continue
        try:
            c=urllib2.urlopen(myUrl)
        except:
            continue
        soup = BeautifulSoup(c.read())
        links = soup('a')
        for link in links:
            if('href' in dict(link.attrs)):
                url = urljoin(myUrl,link['href'])
                if url.find("'")!=-1: continue
                url=url.split('#')[0]
                if url[0:4] == 'http':
                    print url
                    q_new.put(url)




q_start = Queue.Queue()

q_new = Queue.Queue()



for i in range(20):
        t = Thread(target=doWork)
        t.daemon = True
        t.start()


q_start.put("http://google.com")
print "loading"
q_start.join()
print "end"
Run Code Online (Sandbox Code Playgroud)

pil*_*row 4

join()将阻塞,直到task_done()被调用的次数与入队的项目的次数一样多

您不调用task_done(),因此join()会阻塞。在您提供的代码中,调用它的正确位置是在循环的最后doWork

def doWork():
  while True:
    task = start_q.get(False)
    ...
    for subtask in processed(task):
      ...
    start_q.task_done()  # tell the producer we completed a task
Run Code Online (Sandbox Code Playgroud)