Python Multiprocessing 共享全局值 [英] Python Multiprocessing sharing of global values
问题描述
我想做的是让每个进程都使用全局变量.但我的过程并没有采取全球价值观
What i am trying to do is to make use of global variable by each process. But my process is not taking the global values
import multiprocessing
count = 0
def smile_detection(thread_name):
global count
for x in range(10):
count +=1
print thread_name,count
return count
x = multiprocessing.Process(target=smile_detection, args=("Thread1",))
y = multiprocessing.Process(target=smile_detection, args=("Thread2",))
x.start()
y.start()
我得到的输出像
Thread1 1
Thread1 2
.
.
Thread1 9
Thread1 10
Thread2 1
Thread2 2
.
.
Thread2 9
Thread2 10
我想要的是
Thread1 1
Thread1 2
.
.
Thread1 9
Thread1 10
Thread2 11
Thread2 12
.
.
Thread2 19
Thread2 20
我必须做什么才能实现这一目标?
What I have to do to achieve this?
推荐答案
与线程不同,由于分叉(或产生)新进程,多处理处理共享状态有点棘手.尤其是在窗户上.要拥有共享对象,请使用 multiprocessing.Array 或 multiprocessing.Value.在数组的情况下,您可以在每个进程中取消引用另一个结构中的内存地址,例如 numpy 数组.在你的情况下,我会做这样的事情:
Unlike threading, multiprocessing is a bit trickier to handle shared state due to forking (or spawning) of a new process. Especially in windows. To have a shared object, use a multiprocessing.Array or multiprocessing.Value. In the case of the array, you can, in each process, dereference its memory address in another structure, e.g an numpy array. In your case, I would do something like this:
import multiprocessing, ctypes
count = multiprocessing.Value(ctypes.c_int, 0) # (type, init value)
def smile_detection(thread_name, count):
for x in range(10):
count.value +=1
print thread_name,count
return count
x = multiprocessing.Process(target=smile_detection, args=("Thread1", count))
y = multiprocessing.Process(target=smile_detection, args=("Thread2", count))
x.start()
y.start()
这篇关于Python Multiprocessing 共享全局值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!