线程中全局变量的作用域如何工作?

我有两个线程正在运行,我希望它们使用 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 以便可以通过障碍。怎么了?


HUX布斯
浏览 81回答 1
1回答

翻阅古今

您可以利用队列在线程之间共享数据。我不确定此代码是否会根据您的用例工作,但您可以执行以下操作:import threading, queuelock = threading.Condition()q = queue.Queue()q.put(0)n = 2def 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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python