python ThreadLocal

ThreadLocal:

主要是为了解决各个线程引用全局变量,并且各个线程之间互不影响而设置的。

实例:

import threading

threadlocal = threading.local()

def process_student():
std = threadlocal.student
print('Student %s in %s' % (std,threading.current_thread().name))

def thread_student(name):
threadlocal.student = name #将参数赋值给线程全局变量threadlocal.student
process_student() #相当于引用传递threadlocal.student参数

t1 = threading.Thread(target=thread_student,args=('boh',),name='ThreadA')
t2 = threading.Thread(target=thread_student,args=('lucy',),name='ThreadB')
t1.start()
t2.start()
t1.join()
t2.join()

猜你喜欢

转载自www.cnblogs.com/wuchenggong/p/8858813.html