在线程中使用全局变量 [英] Using a global variable with a thread

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

问题描述

如何与线程共享全局变量?

How do I share a global variable with thread?

我的Python代码示例是:

My Python code example is:

from threading import Thread
import time
a = 0  #global variable

def thread1(threadname):
    #read variable "a" modify by thread 2

def thread2(threadname):
    while 1:
        a += 1
        time.sleep(1)

thread1 = Thread( target=thread1, args=("Thread-1", ) )
thread2 = Thread( target=thread2, args=("Thread-2", ) )

thread1.join()
thread2.join()

我不知道如何让两个线程共享一个变量.

I don't know how to get the two threads to share one variable.

推荐答案

您只需要在thread2中将a声明为全局变量,这样就不会修改该函数本地的a

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):
    global a
    while True:
        a += 1
        time.sleep(1)

thread1中,您不需要做任何特殊的事情,只要您不尝试修改a的值(这将创建一个遮盖全局变量的局部变量;请使用(如果需要)>

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):
    #global a       # Optional if you treat a as read-only
    while a < 10:
        print a

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

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