名稱空間
變體
操作

tss_create

來自 cppreference.com
< c‎ | thread
在標頭檔案 <threads.h> 中定義
int tss_create( tss_t* tss_key, tss_dtor_t destructor );
(C11 起)

建立新的執行緒區域性儲存鍵,並將其儲存在 tss_key 指向的物件中。儘管不同的執行緒可以使用相同的鍵值,但透過 tss_set 繫結到鍵的值是按執行緒維護的,並持續到呼叫執行緒的生命週期結束。

在所有現有執行緒中,新建立的鍵都關聯 NULL 值,並且線上程建立時,所有 TSS 鍵關聯的值都被初始化為 NULL

如果 destructor 不是空指標,那麼當儲存被 thrd_exit 釋放時(但不是透過 tss_delete,也不是在程式終止時透過 exit),將呼叫此解構函式。

線上程區域性儲存解構函式中呼叫 tss_create 會導致未定義行為。

目錄

[編輯] 引數

tss_key - 指向記憶體位置的指標,用於儲存新的執行緒區域性儲存鍵
解構函式 - 指向執行緒退出時呼叫的函式的指標

[編輯] 注意

此函式在 POSIX 中的等價函式是 pthread_key_create

[編輯] 返回值

如果成功則為 thrd_success,否則為 thrd_error

[編輯] 示例

int thread_func(void *arg) {
    tss_t key;
    if (thrd_success == tss_create(&key, free)) {
        tss_set(key, malloc(4)); // stores a pointer on TSS
        // ...
    }
} // calls free() for the pointer stored on TSS

[編輯] 參考資料

  • C17 標準 (ISO/IEC 9899:2018)
  • 7.26.6.1 The tss_create function (p: 281-282)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.26.6.1 The tss_create function (p: 386)