我们可以在线程类外定义变量,并在类的方法内声明它是全局的。
请参阅下面的小例子,其中打印AB交替。两个变量flag和val在两个线程Thread_A和Thread_B之间共享。Thread_A打印val=20,然后将val设置为30。Thread_B打印val=30,因为val在Thread_A中被修改。Thread_B然后将val设置为20,这将再次用于Thread_A。这表明变量val在两个线程之间共享。同样,变量flag也在两个线程之间共享。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
每个线程打印在另一个线程中修改的值。