Python3
Ubuntu虚拟机
打开VMware虚拟化软件,启动Ubuntu虚拟机,登录系统,在桌面空白处右键鼠标,打开终端。
在终端使用gedit编辑器,创建一个‘testlocal.py’文件,命令如下:gedit testlocal.py
在终端运行代码python3 testlocal.py结果如下图,每个线程都打印出了两次Student.name,而且如何还有内层的函数传递参数比较麻烦
不使用传递参数的方法,可以使用全局字典的方法,修改代码如下:from threading import Thread,current_thread class Student: def __init__(self,name): self.name = nameglobal_dict = {}def pro_func(name): std = Student(name) global_dict[current_thread()] = std task1() task2() def task1(): std = global_dict[current_thread()] print ('我是task1:'+std.name) def task2(): std = global_dict[current_thread()] print ('我是task2:'+std.name) t1 = Thread(target=pro_func,args=('denny',))t2 = Thread(target=pro_func,args=('andy',))t1.start()t1.join()t2.start()t2.join()
在终端运行代码python3 testlocal.py结果如下图,这样尽管没有传递变量的问题,但是每个线程依然不能单独处理不同Student对象。
修改代码使用ThreadLocal对象,代码如下:from threading import Thread,current_thread,local localstd = local()def pro_func(name): localstd.name = name task() def task(): print ('我是task:'+localstd.name) t1 = Thread(target=pro_func,args=('denny',))t2 = Thread(target=pro_func,args=('andy',))t1.start()t1.join()t2.start()t2.join()全局变量localstd就是一个ThreadLocal对象,每个线程都可以读写它的name属性,互不影响。
在终端运行代码python3 testlocal.py结果如下图,对于每个线程而言,localstd.name都是线程的局部变量,实现了单独处理不同Student对象的功能。
ThreadLocal最常用的是为每个线程绑定一个数据库连接,Http请求、用户身份信息等