Python threading and sharing variables

Thomas Nyberg tomuxiong at gmx.com
Wed Jul 5 04:20:16 EDT 2017


On 07/05/2017 09:56 AM, pozz wrote:
> It seems it works, but I'm not sure it is the correct way to share the
> variable self.cnt. It is only written in the long thread and only read
> in the main thread.
> Could a single Python instruction be interrupted (in this case, self.cnt
> = i)? Should I use a locking mechanism when reading/writing?
> 
> What about if the variable is more complex, for example a list or
> dictionary? Even in this case, is it safe to avoid locking on a shared
> variable if the operation on the variable is performed in a single
> Python instruction?

I think it would be clearer if you used a queue. Here's an example of
simplified version showing how the communication might work:

test.py
---------------------------
from threading import Thread
from queue import Queue
from time import sleep


def main():
    q = Queue()
    t = Thread(target=worker, args=(q,))
    t.start()
    while True:
        status = q.get()
        if status < 0:
            break
        print(status)
    t.join()


def worker(q, limit=5):
    for i in range(limit):
        sleep(1) # Simulate some work
        q.put(i)
    q.put(-1) # Some sort of value to indicate being finished


main()
--------------------------------

$ python3 test.py
0
1
2
3
4


Not sure if this helps, but I personally find it clearer than the shared
class variable method you're using.

Cheers,
Thomas



More information about the Python-list mailing list