【问题标题】:Infinite Loop Exits Automatically while Using multithreading and Queues使用多线程和队列时无限循环自动退出
【发布时间】:2016-10-08 21:41:12
【问题描述】:

我正在尝试使用多线程运行一个具有无限循环的函数(延迟几秒钟后检查数据)。由于我从 csv 文件中读取数据,因此我也在使用队列。

当我不使用多线程/队列时,我当前的函数很好,但是当我使用它们时,该函数只循环一次然后停止。

这是我的函数,它有一个无限循环。请注意,第一个 while True 循环用于线程(如果我使用的线程数少于 csv 中的行数),该函数只需要第二个 while True 循环。

def doWork(q):
    while True:
        #logging.info('Thread Started')
        row=q.get()

        url = row[0]
        target_price = row[1]
        #logging.info('line 79')

        while True:
            delay=randint(5,10)
            headers = {'User-Agent': generate_user_agent()}
            print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')+': '+'Sleeping for ' + str(delay) + ' seconds'
            #logging.info('line 81')
            eventlet.sleep(delay)
            try:
                #logging.info('line 85')
                with requests.Session() as s:
                    #logging.info('line 87')
                    with eventlet.Timeout(10, False):
                        page = s.get(url,headers=headers,proxies=proxyDict,verify=False)
                    #logging.info('line 89')
                    tree = html.fromstring(page.content)
                    #logging.info('line 91')
                    price = tree.xpath('//div[@class="a-row a-spacing-mini olpOffer"]/div[@class="a-column a-span2 olpPriceColumn"]/span[@class="a-size-large a-color-price olpOfferPrice a-text-bold"]/text()')[0]
                    title = tree.xpath('//h1/text()')[0]
                    #logging.info('line 93')
                    new_price = re.findall("[-+]?\d+[\.]?\d+[eE]?[-+]?\d*", price)[0]
                    #logging.info('line 95')
                    old_price = new_price
                    #logging.info('line 97')
                    #print price
                    print new_price
                    print title + 'Current price:' + new_price
                    if float(new_price)<float(target_price):
                        print 'Lower price found!'
                        mydriver = webdriver.Chrome()
                        send_simple_message()
                        login(mydriver)
                        print 'Old Price: ' + old_price
                        print 'New Price: ' + new_price
                    else:
                        print 'Trying again'
                q.task_done()   
            except Exception as e:
                print e
                print 'Error!'
                q.task_done()

这是我的线程驱动函数;

q = Queue(concurrent * 2)

if __name__ == "__main__":

    for i in range(concurrent):
        t = Thread(target=doWork,args=(q,))
        t.daemon = True
        t.start()
    try:
        with open('products.csv','r') as f:
            reader = csv.reader(f.read().splitlines())
            for row in reader:
                q.put((row[0],row[1]))
        q.join()
    except KeyboardInterrupt:
        sys.exit(1) 

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    对于面临相同问题的任何人,这是我解决它的方法。

    我从 while 循环中删除了 q.task_done() 并将其放在 while 循环之外。这按预期工作,但我不确定这是否是正确的方法。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 2016-11-07
      • 2023-03-13
      • 2015-02-07
      • 2020-06-06
      • 2016-04-11
      • 1970-01-01
      相关资源
      最近更新 更多