How Does The Scope Of The Global Variable In Threads Work?
I have two threads running and I want them to wait for each other at a specific line using threading.Condition(). However it seems that the global variable v is not global. It is a
Solution 1:
You can make use of the queue to make share data between threads. I am not sure if this code will work according to your use case but you can do something like this:
import threading, queue
lock = threading.Condition()
q = queue.Queue()
q.put(0)
n = 2
def barrier():
with lock:
v_increase = q.get() + 1
q.put(v_increase)
print("v is increased to " + str(v_increase))
if v_increase == n:
print("v is equal to n")
lock.notifyAll()
print("v equals n")
q.get()
q.put(0)
else:
lock.wait()
class ServerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global v
print("before barrier")
barrier()
print("after barrier")
for i in range(2):
t = ServerThread()
t.start()
Post a Comment for "How Does The Scope Of The Global Variable In Threads Work?"