问题
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 different variable for each thread. Here is the minimum viable product:
import threading
lock = threading.Condition()
v = 0
n = 2
def barrier():
with lock:
global v
v =+ 1
print("v is increased to " + str(v))
if v == n:
print("v is equal to n")
lock.notifyAll()
print("v equals n")
v = 0
else:
lock.wait()
class ServerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("before barrier")
barrier()
print("after barrier")
for i in range(2):
t = ServerThread()
t.start()
The output is such as this:
before barrier
v is increased to 1
before barrier
v is increased to 1
but I want v to be increased to 2 by the second thread so the barrier can be passed. What is wrong?
回答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()
来源:https://stackoverflow.com/questions/60185499/how-does-the-scope-of-the-global-variable-in-threads-work