0

i'm struggling trying to make my thread read variables located outside of it.

Here's the code:

lst = []

class InstancesManager(object):

...

    def start_thread(self):
        process = multiprocessing.Process(target=self.checker)
        process.daemon = True
        process.start()

    def checker(self):
        global lst
        while True:
             print lst
             time.sleep(5)

...

global lst
manager = InstancesManager()
lst.append('foo')
manager.start_thread()
lst.append('bar')

The problem is: thread always prints lst as ['foo'], despite of any changes i performed with it. I tried to save lst as class variable and access like "print self.lst" and "manager.lst.append('bar')" but result is always the same.

How can i make my thread see changes in variables from main program?

Ori Pessach
  • 6,777
  • 6
  • 36
  • 51
Myam
  • 43
  • 2

2 Answers2

3

Your thread isn't a thread - it's a process. It gets its own copy of the global variables.

For real threading (with all its caveats) look at the threading module:

https://docs.python.org/2/library/threading.html#module-threading

Ori Pessach
  • 6,777
  • 6
  • 36
  • 51
-1

I do not know much of Python, but unless all it's variables are atomic by default (which I doubt would be the case) variables accessed from multiple threads should be either atomic, or mutex-protected.

This would still be true after multi-process will be changed to actual multi-threading (I didn't know that it was the case).

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • I wonder why it was downvoted. – SergeyA Sep 01 '15 at 14:39
  • 2
    Probably because it doesn't answer the question. – Ori Pessach Sep 01 '15 at 14:43
  • @SergeyA You didn't correctly identify the OP's actual problem, you admitted that you don't know Python, and then you nevertheless provided incorrect information about it. – Sneftel Sep 01 '15 at 14:56
  • @Sneftel, what exactly was incorrect in my answer? – SergeyA Sep 01 '15 at 15:04
  • In Python, most operations on primitive types are atomic. And even if they weren't, the use of the GIL means that adding to the list from one thread, and accessing the list from another thread, would be safe. – Sneftel Sep 01 '15 at 15:09
  • @Sneftel, oh! OK, I was fully out of line here. Had no idea. Ok, the downvote is totally appropriate. – SergeyA Sep 01 '15 at 15:13