[英]How to make my code to not run sequentially in Python using multithreading
I created simple code which sum the array using Python and multithreading, but I know that It works sequentially.我创建了简单的代码,它使用 Python 和多线程对数组求和,但我知道它是按顺序工作的。 My question is, how can I change my code to not work sequentially using multithreading?
我的问题是,如何将我的代码更改为不使用多线程按顺序工作? The code:
编码:
import threading
def sum(n, **totalSum):
sumThreads['sumThreads'] += matrix[n]
sumThreads = {"sumThreads":0}
for i in range(len(matrix)):
t = threading.Thread(target=sum, args=(i,), kwargs=sumThreads)
t.start()
t.join()
print("Suma: ",sumThreads['sumThreads'])
I tried to achive it using multiprocessing like so:我尝试使用多处理来实现它,如下所示:
if __name__ == '__main__':
import multiprocessing
my_input = [6,5,4,3,2,1,0]
# Pool over all CPUs
print(sum(multiprocessing.Pool().map(int, my_input)))
but I need to use multithreading.但我需要使用多线程。 Any help would be greatly appreciated!
任何帮助将不胜感激!
You cannot share your list my_input
between processes.您不能在进程之间共享您的列表
my_input
。 A good strategy is to split your data into small chunks then compute partial data and finally process all partial results:一个好的策略是将数据分成小块,然后计算部分数据,最后处理所有部分结果:
You code could be:您的代码可能是:
import multiprocessing as mp
import time
import random
CHUNKSIZE = 5
def partial_sum(l):
# Include a latency for demo
time.sleep(random.random())
s = sum(l)
print(f"Sum of {str(l):<15}: {s:>3}")
return s
if __name__ == '__main__':
my_input = range(100)
chunks = (my_input[i:i+CHUNKSIZE]
for i in range(0, len(my_input), CHUNKSIZE))
with mp.Pool(mp.cpu_count()) as pool:
global_sum = sum(pool.map(partial_sum, chunks))
print('---------------------------')
print(f"Global total: {global_sum}")
Output: Output:
Sum of range(35, 40) : 185
Sum of range(5, 10) : 35
Sum of range(70, 75) : 360
Sum of range(50, 55) : 260
Sum of range(55, 60) : 285
Sum of range(10, 15) : 60
Sum of range(45, 50) : 235
Sum of range(40, 45) : 210
Sum of range(95, 100) : 485
Sum of range(25, 30) : 135
Sum of range(75, 80) : 385
Sum of range(90, 95) : 460
Sum of range(20, 25) : 110
Sum of range(60, 65) : 310
Sum of range(30, 35) : 160
Sum of range(85, 90) : 435
Sum of range(65, 70) : 335
Sum of range(15, 20) : 85
Sum of range(80, 85) : 410
Sum of range(0, 5) : 10
---------------------------
Global total: 4950
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.