在Python中進行并行計算求和可以通過使用多進程或多線程來實現。以下是使用多進程和多線程的示例代碼:
import multiprocessing
def sum_worker(data_chunk, result_queue):
result = sum(data_chunk)
result_queue.put(result)
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk_size = len(data) // 4
result_queue = multiprocessing.Queue()
processes = []
for i in range(4):
start = i * chunk_size
end = start + chunk_size
p = multiprocessing.Process(target=sum_worker, args=(data[start:end], result_queue))
processes.append(p)
p.start()
for p in processes:
p.join()
total_sum = 0
while not result_queue.empty():
total_sum += result_queue.get()
print(total_sum)
import threading
def sum_worker(data_chunk, result_list):
result = sum(data_chunk)
result_list.append(result)
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk_size = len(data) // 4
result_list = []
threads = []
for i in range(4):
start = i * chunk_size
end = start + chunk_size
t = threading.Thread(target=sum_worker, args=(data[start:end], result_list))
threads.append(t)
t.start()
for t in threads:
t.join()
total_sum = sum(result_list)
print(total_sum)
這些代碼示例中,將數據分成4個部分,然后分別使用多進程和多線程來計算每個部分的和,最后將結果匯總得到總和。在實際應用中,可以根據需要調整數據分割的方式和線程/進程數量來實現更高效的并行計算。