问题描述
我正在使用线程"模块在Python中进行项目开发.
I'm working on a project in Python using the "thread" module.
如何创建一个全局变量(在我的情况下,我需要为True或False),以便项目中的所有线程(大约4-6)都可以访问?
How can I make a global variable (in my case I need it to be True or False) that all the threads in my project (about 4-6) can access?
推荐答案
我们可以在线程类外部定义变量,并在类的方法内部将其全局声明.
We can define the variable outside the thread classes and declare it global inside the methods of the classes.
请参见下面的简单示例,该示例交替打印AB.两个线程Thread_A
和Thread_B
之间共享两个变量flag
和val
. Thread_A
打印val=20
,然后将val
设置为30.Thread_B
打印val=30
,因为在Thread_A
中修改了val
. Thread_B
然后将val
设置为20,再次在Thread_A
中使用.这说明了变量val
在两个线程之间共享.同样,两个线程之间也共享变量flag
.
Please see below trivial example which prints AB alternatively. Two variables flag
and val
are shared between two threads Thread_A
and Thread_B
. Thread_A
prints val=20
and then sets val
to 30. Thread_B
prints val=30
, since val
is modified in Thread_A
. Thread_B
then sets val
to 20 which is again used in Thread_A
. This demonstrates that variable val
is shared between two threads. Similarly variable flag
is also shared between two threads.
import threading
import time
c = threading.Condition()
flag = 0 #shared between Thread_A and Thread_B
val = 20
class Thread_A(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
global flag
global val #made global here
while True:
c.acquire()
if flag == 0:
print "A: val=" + str(val)
time.sleep(0.1)
flag = 1
val = 30
c.notify_all()
else:
c.wait()
c.release()
class Thread_B(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
global flag
global val #made global here
while True:
c.acquire()
if flag == 1:
print "B: val=" + str(val)
time.sleep(0.5)
flag = 0
val = 20
c.notify_all()
else:
c.wait()
c.release()
a = Thread_A("myThread_name_A")
b = Thread_B("myThread_name_B")
b.start()
a.start()
a.join()
b.join()
输出看起来像
A: val=20
B: val=30
A: val=20
B: val=30
A: val=20
B: val=30
A: val=20
B: val=30
每个线程都会打印在另一个线程中修改的值.
Each thread prints the value which was modified in another thread.
这篇关于Python在线程之间创建共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!