python thread local的用法,, python
python thread local的用法,, python
python 中多线程的并发跟其他语言一样,需要考虑多线程并发访问去全局变量所带来的问题,python的local类解决了这个问题,通过它让每个线程内部有一个相对独立的local保存数据,某一个线程修改了数据,不影响其他线程中保存的数据。
1 from threading import Thread 2 import threading 3 import time 4 local_value=threading.local() 5 local_value.x=‘en‘ 6 class threadtest(Thread): 7 8 def __init__(self,num): 9 Thread.__init__(self)10 self.num=num11 12 def run(self):13 local_value.x=self.getName()14 for i in range(self.num):15 time.sleep(1)16 print(local_value)17 18 19 threadtest(3).start()20 threadtest(2).start()
执行结果是:
Thread-1Thread-2Thread-1Thread-2Thread-1[Finished in 3.2s]
这表明,虽然两个线程公用一个local_value.x但是确实相互独立的变量。
另外,当
local_value.x=self.getName()放在__init__()中时,运行会报错,说‘_thread._local‘ object has no attribute ‘x‘,还不知道什么问题,但是还是先去吃饭吧。
python thread local的用法
相关内容
- 暂无相关文章
评论关闭