Python多线程处理数组:避免重复处理元素并按序执行
100元素数组的多线程无重复处理
要实现5个线程处理100个元素且无重复,有两种高效的实现方式:
方式一:固定分块分配
把100个元素平均分成5份(每份20个),每个线程负责处理自己的块。这种方式无需额外同步机制,实现简单直接:
import threading def process_chunk(chunk): for item in chunk: # 替换为你的实际处理逻辑 print(f"线程{threading.current_thread().name}处理元素: {item}") # 示例100元素数组 my_array = list(range(100)) chunk_size = len(my_array) // 5 threads = [] for i in range(5): start = i * chunk_size # 处理最后一块(若总数无法整除时,这里刚好整除) end = start + chunk_size if i != 4 else len(my_array) chunk = my_array[start:end] thread = threading.Thread(target=process_chunk, args=(chunk,), name=f"Thread-{i+1}") threads.append(thread) thread.start() # 等待所有线程执行完毕 for thread in threads: thread.join()
方式二:线程安全队列分配
如果不需要固定分块,用queue.Queue存储所有元素,每个线程从队列中取元素处理,直到队列为空。队列本身是线程安全的,能保证每个元素仅被处理一次:
import threading import queue def process_queue(q): while not q.empty(): try: item = q.get(timeout=1) # 超时设置避免线程无限阻塞 # 替换为你的实际处理逻辑 print(f"线程{threading.current_thread().name}处理元素: {item}") q.task_done() except queue.Empty: break # 示例100元素数组 my_array = list(range(100)) q = queue.Queue() for item in my_array: q.put(item) threads = [] for i in range(5): thread = threading.Thread(target=process_queue, args=(q,), name=f"Thread-{i+1}") threads.append(thread) thread.start() q.join() # 等待队列中所有任务完成 for thread in threads: thread.join()
示例数组的分块顺序处理
针对my_list = ["a", "b", "c", "d", "e", "f", "g", "h"],要4个线程各处理2个元素且保持原顺序,核心是按顺序分块+结果按索引拼接:
import threading # 用索引对应存储每个线程的处理结果,保证顺序 results = [None] * 4 def process_chunk_with_index(chunk, index): # 替换为你的实际处理逻辑,示例为转大写 processed = [item.upper() for item in chunk] results[index] = processed my_list = ["a", "b", "c", "d", "e", "f", "g", "h"] chunk_size = 2 threads = [] for i in range(4): start = i * chunk_size end = start + chunk_size chunk = my_list[start:end] thread = threading.Thread(target=process_chunk_with_index, args=(chunk, i)) threads.append(thread) thread.start() # 等待所有线程完成 for thread in threads: thread.join() # 按索引顺序拼接结果,保持原数组顺序 final_result = [] for res in results: final_result.extend(res) print("最终处理结果(保持顺序):", final_result)
每个线程处理连续的2个元素,处理后的结果存在对应索引的位置,最后按索引顺序拼接即可保证和原数组顺序一致。
内容的提问来源于stack exchange,提问作者Djangooow
相关产品推荐
相关产品推荐

