Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a global variable with a thread

How do I share a global variable with thread?

My Python code example is:

from threading import Thread import time a = 0  #global variable  def thread1(threadname):     #read variable "a" modify by thread 2  def thread2(threadname):     while 1:         a += 1         time.sleep(1)  thread1 = Thread( target=thread1, args=("Thread-1", ) ) thread2 = Thread( target=thread2, args=("Thread-2", ) )  thread1.join() thread2.join() 

I don't know how to get the two threads to share one variable.

like image 629
Mauro Midolo Avatar asked Nov 05 '13 13:11

Mauro Midolo


People also ask

Can threads use global variables?

But to answer your question, any thread can access any global variable currently in scope. There is no notion of passing variables to a thread. It has a single global variable with a getter and setter function, any thread can call either the getter or setter at any time.

Can threads modify global variables?

Almost certainly. I answered the question in a very narrow sense: how do I modify a global variable, without any consideration for how you modify it safely.

Are Python global variables thread safe?

We can protect the global variable from race conditions by using a mutual exclusion lock via the threading. Lock class. First, we can create a lock at the same global scope as the global variable. Each time the global variable is read or modified, it must be done so via the lock.


1 Answers

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):     global a     while True:         a += 1         time.sleep(1) 

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):     #global a       # Optional if you treat a as read-only     while a < 10:         print a 
like image 172
chepner Avatar answered Oct 10 '22 04:10

chepner