简体   繁体   English

进程间通信 Python

[英]Communicating between processes Python

I am trying to work out the solution that a process would tell the other process that some values have changed.我正在尝试找出一个进程会告诉另一个进程某些值已更改的解决方案。

import multiprocessing
import time

class Consumer(multiprocessing.Process):
    def __init__(self, share):
        super().__init__()
        self.share = share
        
    def run(self):
        print (self.share)
        self.share = "xxx"
        
share = "ssss"

A = Consumer(share)
B = Consumer(share)

if __name__ == '__main__':
    A = Consumer(share)
    A.start()
    time.sleep(5)
    B = Consumer(share)
    B.start()

expecting to have "xxx" to be printed when B runs.期望在 B 运行时打印“xxx”。 but got "ssss" as initial value.但将“ssss”作为初始值。

after some researches, multiprocess.manager package can be used to achieve it.经过一些研究,multiprocess.manager package 可以用来实现它。 But due to the concerns of speed, ie 100 processes, with high frequency of accessing the share value, the lock would become a bottleneck.但是出于速度的考虑,即100个进程,访问share值的频率很高,锁会成为瓶颈。

Is there way to be able to lock the object when change the value but reading??有没有办法在更改值但读取时能够锁定 object?

Use a manager to share objects across processes:使用manager跨进程共享对象:

import multiprocessing
import time

class Consumer(multiprocessing.Process):
    def __init__(self, manager_namespace):
        super().__init__()
        self.share = manager_namespace

    def run(self):
        print (self.share.myString)
        self.share.myString = "xxx"



if __name__ == '__main__':

    manager = multiprocessing.Manager()
    namespace = manager.Namespace()
    namespace.myString = 'sss'

    B = Consumer(namespace)
    A = Consumer(namespace)
    A.start()
    time.sleep(5)
    B = Consumer(namespace)
    B.start()

At least in my system it gives the required output.至少在我的系统中,它提供了所需的 output。

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

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