线程中全局变量的作用域如何工作? [英] How does the scope of the global variable in threads work?

查看:98
本文介绍了线程中全局变量的作用域如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个正在运行的线程,我希望它们使用threading.Condition()在特定的行上互相等待.但是,似乎全局变量v不是全局变量.对于每个线程,它是一个不同的变量.这是最低可行的产品:

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()

输出如下:

before barrier
v is increased to 1
before barrier
v is increased to 1

但是我希望第二个线程将v增加到2,以便可以传递障碍.怎么了?

but I want v to be increased to 2 by the second thread so the barrier can be passed. What is wrong?

推荐答案

您可以利用队列在线程之间共享数据.我不确定此代码是否可以根据您的用例工作,但是您可以执行以下操作:

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()

这篇关于线程中全局变量的作用域如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆