3

I need to share variables across multiple modules. These variables will be changed asynchronously by threads as the program runs.

I need to be able to access the most resent state of the variable by multi modules at the same time.

Multiple modules will also be writing to the same variable.

Basically what I need is a shared memory space, like a Global var within a module, but is accessible & changeable by all other modules asynchronously.

I'm familiar with locking a global variable within a module. I have no idea where to start doing this across multiple modules.

How is it done?

Emily
  • 2,129
  • 3
  • 18
  • 43
  • this might help. http://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable – ham Oct 13 '16 at 08:33
  • Any unintended consequences? And/or I assume a var can be locked while changing the __builtin__ var? Is this the way it is generally done? – Emily Oct 13 '16 at 08:40
  • You can have a look at how its done for `django.settings` vars. I think that should be how its done. Maintaining a parent module for such variables. – ham Oct 13 '16 at 08:43

1 Answers1

3

Place all your global variables in a module, for example config.py and import it throughout your modules:

config.py:

a=None
varlock=None

main.py:

import config
import threading

config.a = 42
config.varlock = threading.RLock()
...

Then you can use the global lock instance, instantiated once in your main, to protect your variables. Every time you modify one of these in any of your threads, do it as

with config.varlock:
    config.a = config.a + 42

and you should be fine.

Hannu

Hannu
  • 11,685
  • 4
  • 35
  • 51
  • Why instantiate in main? Any reason not keep it all in config.py, then import config into all the modules? – Emily Oct 13 '16 at 15:44
  • Doesn't really matter as long as you create the RLock instance only once. If you do it wrong, you might end up creating several lock instances, in which case they would not work. I use global variables and threads quite a lot and my modus operandi is to include config.py everywhere, in main.py instantiate all locks, then fire threads and off I go. This ensures there is no parallelism when setting up those things that are supposed to be global and "static", for example locks. – Hannu Oct 14 '16 at 12:31