Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top