我有两个正在运行的线程,我希望它们使用threading.Condition()在特定的行上互相等待。但是,似乎全局变量v不是全局变量。每个线程的变量都不同。这是最低可行的产品:
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()
输出是这样的:
before barrier
v is increased to 1
before barrier
v is increased to 1
但是我希望第二个线程将v增加到2,以便可以传递障碍。怎么了?
您可以利用队列在线程之间共享数据。我不确定此代码是否会根据您的用例工作,但是您可以执行以下操作:
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()