Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a variable between 2 threads

Using Python 2.7.3 on Windows.

How can I share a variable num between threads, such that, after num is squared, it is printed?

I realized that I need to understand how threads work, but docs don't have much, and I haven't found anything here either..
So, could someone explain how threads work and how to share variables between 2 threads?

My code (keeps printing 2)

import threading
def func1(num):
    while num < 100000000:
        num =  num**2
def func2(num):
    while num < 100000000:
        print num,
num = 2
thread1 = threading.Thread(target=func1,args=(num,))
thread2 = threading.Thread(target=func2,args=(num,))
print 'setup'
thread1.start()
thread2.start()
like image 543
pradyunsg Avatar asked Mar 17 '13 13:03

pradyunsg


People also ask

How do I share a variable between two threads?

You should use volatile keyword to keep the variable updated among all threads. Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.

Can two threads access same variable?

Only one thread can read and write a shared variable at a time. When one thread is accessing a shared variable, other threads should wait until the first thread is done.

How do you pass a variable between threads in python?

You can protect data variables shared between threads using a threading. Lock mutex lock, and you can share data between threads explicitly using queue. Queue.

How do you pass data between two threads in Java?

If you want synchronous communication between a main thread and a processing thread, you can use a SynchronousQueue. The idea is that the main thread passes data to the processing thread by calling put() , and the processing thread calls take() . Both are blocking operations.


1 Answers

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.

like image 194
uselpa Avatar answered Oct 14 '22 19:10

uselpa