我正在使用英特尔奔腾(R)双核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()
答案 0 :(得分:1)
答案 1 :(得分:0)
在calc
功能中,您需要将return
更改为print
。在我的四核机器上(运行OS X Mavericks),这是我在终端中运行脚本时的输出。您还应将p1.join()
和p2.join()
作为if __name__ == "__main__
的一部分。
Last login: Sun Feb 15 15:47:18 on ttys001
imac:~ zinedine$ cd '/Users/zinedine/Documents/' && '/usr/local/bin/pythonw'
'/Users/zinedine/Documents/example.py' && echo Exit status: $? && exit 1
number of cores 4
8
4
Exit status: 0
logout
[Process completed]
我在终端中使用的代码......
import multiprocessing
print "number of cores ", 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()
使用Python Launcher.app
后,它在终端打开,它给出了我上面给出的输出......
答案 2 :(得分:0)
我建议您使用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