Linux系統程式設計 執行緒私有資料

2021-09-08 16:35:17 字數 2754 閱讀 5194

在多執行緒程式中,經常要用全域性變數來實現多個函式間的資料共享。由於資料空間是共享的,因此全域性變數也為所有執行緒共有。

測試**如下:

#include

#include

#include

#include

int key =

100;

//全域性變數

由執行結果可以看出,其中乙個執行緒對全域性變數的修改將影響到另乙個執行緒的訪問。

下面介面所需標頭檔案:

#include

intpthread_key_create

(pthread_key_t *key,

void

(*destructor)

(void*)

);

1)建立執行緒私有資料功能:

建立乙個型別為 pthread_key_t 型別的私有資料變數( key )。

引數:

key:在分配( malloc )執行緒私有資料之前,需要建立和執行緒私有資料相關聯的鍵( key ),這個鍵的功能是獲得對執行緒私有資料的訪問權。

destructor:清理函式名字( 如:fun )。當執行緒退出時,如果執行緒私有資料位址不是非 null,此函式會自動被呼叫。該函式指標可以設成 null ,這樣系統將呼叫預設的清理函式。

返回值:

成功:0

失敗:非 0

不論哪個執行緒呼叫 pthread_key_create(),所建立的 key 都是所有執行緒可訪問,但各個執行緒可根據自己的需要往 key 中填入不同的值,相當於提供了乙個同名不同值的變數。

2)登出執行緒私有資料

int

pthread_key_delete

(pthread_key_t key)

;

功能:

登出執行緒私有資料。這個函式並不會檢查當前是否有執行緒正使用執行緒私有資料( key ),也不會呼叫清理函式 destructor() ,而只是將執行緒私有資料( key )釋放以供下一次呼叫 pthread_key_create() 使用。

引數:

key:待登出的私有資料。

返回值:

成功:0

失敗:非 0

3)設定執行緒私有資料的關聯

int

pthread_setspecific

(pthread_key_t key,

const

void

*value)

;

功能:

設定執行緒私有資料( key ) 和 value 關聯,注意,是 value 的值(不是所指的內容)和 key 相關聯。

引數:

返回值:

成功:0

失敗:非 0

4)讀取執行緒私有資料所關聯的值

void

*pthread_getspecific

(pthread_key_t key)

;

功能:

讀取執行緒私有資料( key )所關聯的值。

引數:

key:執行緒私有資料。

返回值:

成功:執行緒私有資料( key )所關聯的值。

失敗:null

示例**如下:

// this is the test code for pthread_key 

#include

#include

#include

pthread_key_t key;

// 私有資料,全域性變數

從執行結果來看,各執行緒對自己的私有資料操作互不影響。也就是說,雖然 key 是同名且全域性,但訪問的記憶體空間並不是同乙個。

(學習複習資料)本文內容來自:

Linux系統程式設計 執行緒私有屬性

在多執行緒程式中,單個執行緒內需要使用全域性變數來實現不同功能之間的共享 在多個執行緒之間由於全域性變數的存在也會在多個執行緒間共享 測試 如下 include include include include include include 1 建立執行緒私有資料 int pthread key c...

多執行緒程式設計 執行緒私有資料(TSD)

thread specific data tsd 執行緒私有資料,有什麼用呢?在多執行緒中,經常要用全域性變數來實現多個函式間的資料共享。由於資料空間是共享的,因此全域性變數也為所有程序共有。但有時應用程式設計中必要提供執行緒私有的全域性變數,這個變數被各個執行緒私有,但卻可以跨過多個函式訪問。書上...

linux系統程式設計 執行緒

include int pthread create pthread t thread,const pthread attr t attr,void start routine void void arg include include include include include include...