gpt4 book ai didi

python - 如何使用python的多处理模块

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:07 25 4
gpt4 key购买 nike

我使用的是 Intel 的 Pentium(R)Dual-core E5700 @3.00GHz 和 2GB 内存。我正在尝试学习 Python 的 multiprocessing 模块。我写了一个简单的程序来执行加法,但它不起作用;我只是越来越多的核心 2。我的电脑或我的代码有问题吗?

import multiprocessing
print "number of core ",multiprocessing.cpu_count()



def calc(a,b):
c= a+b
return c

if __name__ =='__main__':

p1 = multiprocessing.Process(target=calc,args=(3,5) )
p1.start()
p2 = multiprocessing.Process(target=calc,args=(2,2) )
p2.start()



p1.join()
p2.join()

最佳答案

我建议你使用Queue .看这个例子:

from multiprocessing import Queue, Process

def calc(a, b, queue):
queue.put(a + b)

if __name__ == '__main__':
queue = Queue()
p1 = Process(target = calc, args = (4, 4, queue,))
p2 = Process(target = calc, args = (4, 4, queue,))
p1.start()
p2.start()
result_1 = queue.get()
result_2 = queue.get()
print(result_1, result_2)
p1.join()
p2.join()
input()

>>> 8 8

动态相同的代码:

from multiprocessing import Queue, Process, cpu_count

def calc(a, b, queue):
queue.put(a + b)

if __name__ == '__main__':
queue = Queue()
processes = []
for i in range(cpu_count()):
processes.append(Process(target = calc, args = (4, 4, queue,)))
processes[-1].start()
results = []
for i in range(cpu_count()):
results.append(queue.get())
print(results)
for process in processes:
process.join()

>>> [8, 8] # if you have two cores

关于python - 如何使用python的多处理模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28530705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com