[英]Python: Global variables in threads
我试图使我的程序脱机工作。 我决定这样做的方法是让主应用程序在其自己的线程中从内存中工作,而另一个线程从数据库中读取/写入数据。
我在赋值之前被引用的变量有问题。
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()
这与线程无关。 设置
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.