TLS 與 python thread local

TLShtml

先說TLS( Thread Local Storage), wiki上是這麼解釋的:python

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread.編程

線程本地存儲(TLS)是一種電腦編程技術, 它用靜態或者全局的存儲器來保存線程本地的變量(意譯)。spa

 

其目的是爲了實現變量隔離,即「同一個」全局變量,對於不一樣的線程,其值能夠不一樣(相似副本的概念)。參考如下python的實現及說明。線程

 

python thread localhtm

import threading
global_storage=threading.local()

 

副本做用blog

# -*- coding:utf-8 -*-
import threading
global_storage = threading.local()
import time
def test_local():
	time.sleep(1)
	if hasattr(global_storage,'x'):
		global_storage.x+=1
	else:
		global_storage.x=0
	print global_storage.x

if __name__=='__main__':
	for i in range(3):
		threading.Thread(target=test_local).start()

以上代碼將會輸出3個0(x有三個副本)ip

而不是0,1,2(x並不是惟一的單例)utf-8

 

固然,對於單線程來說,thread local 就弱化爲了一個全局變量池get

 

轉載請註明本文來自:http://www.cnblogs.com/Tommy-Yu/p/5459291.html,謝謝!

相關文章
相關標籤/搜索