线程没有从队列中获取更多工作

Threads not picking up more work from Queue

我几乎是 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()

您忘记了在线程中循环 Queue...

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))