简体   繁体   中英

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. but got "ssss" as initial value.

after some researches, multiprocess.manager package can be used to achieve it. But due to the concerns of speed, ie 100 processes, with high frequency of accessing the share value, the lock would become a bottleneck.

Is there way to be able to lock the object when change the value but reading??

Use a manager to share objects across processes:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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