python ThreadLocal

ThreadLocal:

It is mainly set up to solve the problem that each thread references global variables, and each thread does not affect each other.

Example:

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()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324493787&siteId=291194637