I have viewed some other threads that address the problem but not quite get it.
Suppose I have a config file that contains a shared variable:
flag = False
import config
while(1):
config.flag = True
print config.flag
import config
while(1):
config.flag = False
print config.flag
If now I run Test1.py and Test2.py, can I see the switch between 'True' 'False' in the output? I don't care about synchronization at this point, as long as it can access the shared variable, then it's done.
Thanks.
No. As long as you're running both instances in separate processes, memory won't be magically shared.
You're starting two different (Python) processes. Those processes import the config module. Simplified, this is just a form of loading the code in config.py. There is no further communication going between the processes.
(As a side note, the code in config.py is only interpreted the first time, it's compiled and saved in a separate config.pyc which loads much faster. The next time config.py is edited, config.pyc will be recreated).
There are other options:
Example with threads:
flag = False
import thread
import time
import config
def test1():
while 1:
config.flag = True
time.sleep(0.7)
print 'test1:', config.flag
time.sleep(1)
def test2():
while 1:
config.flag = False
time.sleep(1.1)
print 'test2:', config.flag
time.sleep(1)
thread.start_new(test1, ())
test2()
It may be helpful to post the reason you're trying to do this. Multithreading is a difficult topic. This question may be useful: https://stackoverflow.com/questions/4690518/multithreading-in-python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With