How to share a variable between 2 threads

The general answer to this question is queues:

import threading, queue

def func1(num, q):
    while num < 100000000:
        num =  num**2
        q.put(num)

def func2(num, q):
    while num < 100000000:
        num = q.get()
        print num,

num = 2
q = queue.Queue()
thread1 = threading.Thread(target=func1,args=(num,q))
thread2 = threading.Thread(target=func2,args=(num,q))
print 'setup'
thread1.start()
thread2.start()

printing

=== pu@pumbair:~/StackOverflow:507 > ./tst.py
setup
4 16 256 65536 4294967296

Notice that in this (and your) code, num is a local variable in both func1 and func2, and they bear no relationship to each other except that they receive the initial value of the global variable num. So num is not shared here. Rather, one thread puts the value of its num into the queue, and the other binds this value to a local (and thus different) variable of the same name. But of course it could use any name.

Leave a Comment