繁体   English   中英

将列表分成批处理以处理多批处理的每个批处理中的元素

[英]Splitting a list into batches to process elements in each batch multi threaded

我试图将列表中的每个元素传递给一个函数,该函数在自己的线程上开始执行自己的工作。 问题是如果列表中有100多个元素,它将在100个线程上启动100个functions()。

为了我的计算机,我要按以下步骤分十个顺序处理列表:

  1. 批次1排队。
  2. 将每个元素从batch1传递到在其自己的线程上入门的函数(这样,我一次只能运行10个函数线程)
  3. 一旦所有10个线程完成,它们就会从队列中弹出
  4. 重复直到所有批次完成

我试图使用两个列表,其中前10个元素被弹出到list2中。 处理list2后,一旦线程完成,再弹出10个元素,直到list1的长度为0。

我到目前为止还不确定如何进行。

    carsdotcomOptionVal, carsdotcomOptionMakes = getMakes()
    second_list = []

    threads = []

    while len(carsdotcomOptionVal) != 0:
        second_list.append(carsdotcomOptionVal.pop(10))
        for makesOptions in second_list:
            th = threading.Thread(target=getModels, args=[makesOptions])
            th.start()
            threads.append(th)

        for thread in threads:
            thread.join()

最后,主列表中的元素不必是偶数,因为它们可以是奇数。

您应该使用queue.Queue对象,该对象可以为其他“工作线程”创建线程安全的任务列表。 您可以选择活动的工作线程数,它们将从列表中馈送,直到完成为止。

这是带有queue的示例代码的样子:

import queue
import threading

threads_to_start = 10 # or choose how many you want
my_queue = queue.Queue()

def worker():
    while not my_queue.empty():
        data = my_queue.get()
        do_something_with_data(data)
        my_queue.task_done()

for i in range(100):
    my_queue.put(i) # replace "i" with whatever data you want for the threads to process

for i in range(threads_to_start):
    t = threading.Thread(target=worker, daemon=True) # daemon means that all threads will exit when the main thread exits
    t.start()

my_queue.join() # this will block the main thread from exiting until the queue is empty and all data has been processed

请记住,这只是一个伪代码的粗略入门,向您介绍了线程和队列,它不仅仅包含这些内容,但是该示例应该在大多数简单的用例中都可以使用

这也是可扩展的-如果可以支持更多或更少的线程,则只需更改最初在threads_to_start设置的数量即可

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM