Reputation: 4281
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.
Upvotes: 3
Views: 2632
Reputation: 1689
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
Upvotes: 4
Reputation: 4092
No, config.flag will not be shared between Test1.py and Test2.py. Test1.py and Test2.py will be running on separate instances of the Python interpreter. Each interpreting loads config.py into it's own parcel of memory.
One option is to use threading to run Test1.py and Test2.py on the same Python instance.
Another option is to store and continuously load the value from the disk, perhaps by saving it in a text file or maybe using SQLite.
Upvotes: 1