abh*_*hek 5 python shared-memory python-multiprocessing
我想做的是每个过程都使用全局变量。但是我的过程没有采用全球价值观
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()
Run Code Online (Sandbox Code Playgroud)
我正在输出像
Thread1 1
Thread1 2
.
.
Thread1 9
Thread1 10
Thread2 1
Thread2 2
.
.
Thread2 9
Thread2 10
Run Code Online (Sandbox Code Playgroud)
我想要的是
Thread1 1
Thread1 2
.
.
Thread1 9
Thread1 10
Thread2 11
Thread2 12
.
.
Thread2 19
Thread2 20
Run Code Online (Sandbox Code Playgroud)
我必须要做些什么才能做到这一点?
与线程不同,由于新进程的分叉(或生成),多处理在处理共享状态时有点棘手。尤其是在窗户上。要拥有共享对象,请使用 multiprocessing.Array 或 multiprocessing.Value。对于数组,您可以在每个进程中取消引用另一个结构(例如 numpy 数组)中的内存地址。对于你的情况,我会做这样的事情:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2767 次 |
| 最近记录: |