简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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