[英]Splitting a list into batches to process elements in each batch multi threaded
我试图将列表中的每个元素传递给一个函数,该函数在自己的线程上开始执行自己的工作。 问题是如果列表中有100多个元素,它将在100个线程上启动100个functions()。
为了我的计算机,我要按以下步骤分十个顺序处理列表:
我试图使用两个列表,其中前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.