我正在尝试使我的程序脱机工作。我决定这样做的方法是让主应用程序在内存中运行自己的线程,而另一个线程从数据库读取/写入数据。
我在分配之前遇到了引用变量的问题。
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()
答案 0 :(得分:1)
这与线程没有任何关系。设置
global variable
不会将此变量设置为全局,而是仅在该函数中。只需将我的更改添加到您的代码中即可运行。
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