【问题标题】:Threads not picking up more work from Queue线程没有从队列中获取更多工作
【发布时间】:2017-04-10 21:47:34
【问题描述】:

我对 python 非常陌生,我一直在研究一个脚本,它可以解析任何给定目录中的 csv 文件。在我实现了一个队列和线程之后,我一直被困在线程没有接受新工作的问题上,即使队列中还有项目。例如,如果我将最大线程数指定为 3,并且队列中有 6 个项目,则线程会提取 3 个文件,处理它们,然后无限期地挂起。我可能只是在概念上误解了多线程过程。

预计到达时间: 出于安全原因,部分代码已被删除。

q = Queue.Queue()
threads = []

for file in os.listdir(os.chdir(arguments.path)):
            if (file.endswith('.csv')):
                q.put(file)
        for i in range(max_threads):
            worker = threading.Thread(target=process, name='worker-{}'.format(thread_count))
            worker.setDaemon(True)
            worker.start()
            threads.append(worker)
            thread_count += 1
        q.join()

def process():
        with open(q.get()) as csvfile:
            #do stuff
            q.task_done()

【问题讨论】:

    标签: multithreading python-3.x python-multithreading


    【解决方案1】:

    您忘记在线程中循环 队列...

    def process():
        while True: #<---------------- keep getting stuff from the queue
             with open(q.get()) as csvfile:
             #do stuff
                 q.task_done()
    

    也就是说,您可能正在重新发明轮子,请尝试使用 线程池

    from concurrent.futures import ThreadPoolExecutor
    
    l = [] # a list should do it ...
    for file in os.listdir(arguments.path):
            if (file.endswith('.csv')):
                l.append(file)
    
    def process(file):
    
        return "this is the file i got %s" % file
    
    with ThreadPoolExecutor(max_workers=4) as e:
        results = list(e.map(process, l))
    

    【讨论】:

    • 德普。谢谢你。
    猜你喜欢
    • 2021-12-14
    • 2010-09-14
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多