How To Share Mutable Variables Across Python Modules?
<p>I need to share variables across multiple modules.  These variables will be changed asynchronously by threads as the program runs.</p>

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

<p>Multiple modules will also be writing to the same variable.</p>

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

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

<p>How is it done?</p>

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

<p>config.py:</p>

<pre><code>a=None
varlock=None
</code></pre>

<p>main.py:</p>

<pre><code>import config
import threading

config.a = 42
config.varlock = threading.RLock()
...
</code></pre>

<p>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</p>

<pre><code>with config.varlock:
    config.a = config.a + 42
</code></pre>

<p>and you should be fine. </p>

<p>Hannu</p>

python python-multithreading