執行緒區域性儲存(TLS)的使用

2021-09-23 01:33:48 字數 430 閱讀 8643

將執行緒的私有資料(區域性儲存的資料)共享,以供本程序中的其它執行緒使用。

l 適用情形:

執行緒區域性儲存適用於多執行緒共享資料,而又不需要同步的情形。(執行緒同步的開支比較大。)

l 原理

在每個執行緒中有乙個儲存區域,該儲存區域有64個slot(資料槽)。可以通過該slot的索引值(乙個dword數值),獲取指定的slot。每個slot可以設定,也可以取值。slot中的資料是本執行緒中的私有資料。

l 步驟

分配tlsalloc,獲取可用的slot索引。 該值應當為各個執行緒所共享。

設定。tlssetvalue,為指定slot設定值,乙個指標,指向本執行緒中的私有資料區。

取值。tlsgetvalue,從指定slot中取值,乙個指標,指向某個執行緒中的私有資料。

釋放。tlsfree,釋放某個slot,使其可以被其它執行緒使用。

執行緒區域性儲存tls的使用

執行緒區域性儲存 thread local storage,tls 主要用於在多執行緒中,儲存和維護一些執行緒相關的資料,儲存的資料會被關聯到當前執行緒中去,並不需要鎖來維護。因此也沒有多執行緒間資源競爭問題,那如何去實現tls儲存呢,主要有以下幾種方式 gcc和clang的 thread修飾符 w...

執行緒區域性儲存 TLS

本來想通過tid為索引建個表來實現該功能,沒想到已經有現成的機制。單個執行緒的特有資料,介於全域性變數和區域性變數之間。linux 方法一 int pthread key create pthread key t key,void destructor void int pthread key de...

TLS執行緒區域性儲存

為執行緒單獨提供的私有空間 隱式tls thread int number 顯式tls pthread key create pthread getspecific pthread setspecific pthread key delete 隱式tls declspec thread int nu...