python singleton into multiprocessing

前端 未结 5 708
时光取名叫无心
时光取名叫无心 2021-01-13 02:53

How can I code to share the same instance of a \"singletonic\" class among processes?

相关标签:
5条回答
  • 2021-01-13 03:31

    Best is to designate one specific process as owning that instance and dedicated to it; any other process requiring access to that instance obtains it by sending messages to the owning process via a Queue (as supplied by the multiprocessing module) or other IPC mechanisms for message passing, and gets answers back via similar mechanisms.

    0 讨论(0)
  • 2021-01-13 03:34

    I do not think you can share the instance between the processes, but you can have the instance access shared memory: http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes to control it's state if that is really what you want to do.

    However, as stated in other answers, it might be easier to achieve what you want with a Queue.

    0 讨论(0)
  • 2021-01-13 03:41

    You could also use one of the multiprocessing.manager shareable data types

    import multiprocessing as mp
    manager = mp.Manager()
    shared_list = manager.list()
    
    def worker1(l):
        l.append(1)
    
    def worker2(l):
        l.append(2)
    
    process1 = mp.Process(target=worker1, args=[shared_list])
    process2 = mp.Process(target=worker2, args=[shared_list])
    
    process1.start()
    process2.start()
    process1.join()
    process2.join()
    
    print shared_list
    

    output would look like:

    [1, 2]

    There are a variety of data structures on offer but you'll need the parent process to pass in the shared object to the child objects.

    0 讨论(0)
  • 2021-01-13 03:50

    In Python 2.6 the multiprocessing module has a Value object used for sharing state between processes. They have a code sample that should give you an idea of how to share state in this manner, and you can use this approach when writing a singleton class.

    0 讨论(0)
  • 2021-01-13 03:55

    The whole point of processes is to have different address spaces. If you want to share information between processes you must use some means of interprocess communication.

    0 讨论(0)
提交回复
热议问题