简体   繁体   English

Python:线程中的全局变量

[英]Python: Global variables in threads

I am trying to make my program work offline. 我试图使我的程序脱机工作。 The way i decided to to this is to have the main application work from memory in its own thread, whilst another thread read/writes data from the database. 我决定这样做的方法是让主应用程序在其自己的线程中从内存中工作,而另一个线程从数据库中读取/写入数据。

I'm having issues with the variables being referenced before assignment. 我在赋值之前被引用的变量有问题。

import threading

class Data():
        global a
        global b
        a = 1
        b = 1



class A(threading.Thread):
    def run(self):
        while True:
            a += 1


class B(threading.Thread):
    def run(self):
        while True:
            print a
            print b
            b -= 1


a_thr = A()
b_thr = B()
a_thr.start()
b_thr.start()

This does not have anything to do with threads. 这与线程无关。 Setting 设置

global variable

does not set this variable as global everywhere, but only in that function. 不会在任何地方将此变量设置为全局变量,而只能在该函数中设置。 Just add my changes to your code and it should run. 只要将我的更改添加到您的代码中,它就可以运行。

class A(threading.Thread):

    def run(self):
        global a
        global b
        while True:
            a += 1



class B(threading.Thread):

    def run(self):
        global a
        global b
        while True:
            print a
            print b
            b -= 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM