如何与线程共享全局变量?
我的Python代码示例是:
from threading import Thread import time a = 0 #global variable def thread1(threadname): #read variable "a" modify by thread 2 def thread2(threadname): while 1: a += 1 time.sleep(1) thread1 = Thread( target=thread1, args=("Thread-1", ) ) thread2 = Thread( target=thread2, args=("Thread-2", ) ) thread1.join() thread2.join()
我不知道如何让两个线程共享一个变量。
您只需要在中声明a为global thread2,这样就无需修改a该函数本地的。
a
thread2
def thread2(threadname): global a while True: a += 1 time.sleep(1)
在中thread1,您不需要执行任何特殊操作,只要您不尝试修改的值a(这将创建一个局部变量以遮盖全局变量;global a请在需要时使用)>
thread1
global a
def thread1(threadname): #global a # Optional if you treat a as read-only while a < 10: print a