简体   繁体   English

如何从不同的进程访问全局变量

[英]How to access global variables from separate processes

i have two python processes running on different cores that need to communicate between each other while they are running.我有两个 python 进程在不同的内核上运行,它们在运行时需要相互通信。 At the moment i can achieve this via multithreading;目前我可以通过多线程实现这一点;

import threading
x=0
def a():
    global x
    if x==100:
        pass
        #Do something

def b():
    global x
    while 1:
        x=x+1
t1=threading.thread(target=a)
t2=threading.thread(target=b)
t1.start()
t2.start()

But i would like to use the multiprocessing module instead.但我想改用multiprocessing模块。 Is there any way to covert the above code into something using multiprocessing?有没有办法使用多处理将上述代码转换为某些东西?

Here's an example like your original but using multiprocessing...这是一个与您的原始示例类似但使用多处理的示例...

from multiprocessing import Process, Value

def a(x):
    while True:
        if x.value == 10:
            print('Done.  x = ', x.value) 
            break

def b(x):
    for _ in range(10):
        x.value += 1

x = Value('i', 0)   # integer with initial value of 0
t1=Process(target=a, args=(x,))
t2=Process(target=b, args=(x,))
t1.start()
t2.start()

Note that while I did pass in x as a parameter to the function, it looks like this still works if you simply use it as global, as you have above.请注意,虽然我确实将x作为参数传递给 function,但如果您只是将它用作全局,看起来这仍然有效,就像您在上面所做的那样。 The real trick here is to use the multiprocessing.Value object and access it with x.value .这里真正的技巧是使用multiprocessing.Value object 并使用x.value访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM