1. 程式人生 > >執行緒的私有資料(TSD-Thread-Specific Data)

執行緒的私有資料(TSD-Thread-Specific Data)

      線上程內部,執行緒私有資料可以被各個函式訪問到,但它對其他執行緒是遮蔽的。

      使用執行緒資料時,首先要為每個執行緒資料建立一個相關聯的鍵。在各個執行緒內部,都使用這個公用的鍵來指代執行緒資料,但是在不同的執行緒中,這個鍵代表的資料是不同的。也就是說,key一旦被建立,所有執行緒都可以訪問它,但各執行緒可根據自己的需要往key中填入不同的值。這相當於提供了一個同名而不同值的全域性變數,一鍵多值。

      操作執行緒私有資料的函式主要有4個:

  • pthread_key_create(建立一個鍵)
  • pthread_setspecific(為一個鍵設定執行緒私有資料)
  • pthread_getspecific(從一個鍵讀取執行緒私有資料)
  • pthread_key_delete(刪除一個鍵)

      以下程式碼示例如何建立、使用和刪除執行緒的私有資料:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

//宣告鍵
pthread_key_t key;

//執行緒1中設定本執行緒的私有資料為5,並且之後獲取這個資料並列印到螢幕
void * thread1(void *arg)
{
    int tsd=5;
    printf("Thread %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)tsd);
    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
}

//執行緒2中設定本執行緒的私有資料為4,並且之後獲取這個資料並列印到螢幕
void * thread2(void *arg)
{
    int tsd=4;
    printf("Thread %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)tsd);
    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
}

int main(void)
{
    pthread_t thid1,thid2;
    printf("Main thread begins running\n");

	//建立這個鍵
    pthread_key_create(&key,NULL);

	//建立2個子執行緒
    pthread_create(&thid1,NULL,thread1,NULL);
    pthread_create(&thid2,NULL,thread2,NULL);

	//等待2個子執行緒返回
    int status1,status2;
    pthread_join(thid1,(void *)&status1);
    pthread_join(thid2,(void *)&status2);

	//刪除鍵
    pthread_key_delete(key);

    printf("main thread exit\n");
    return 0;
}

執行結果:


      上述2個執行緒分別將tsd作為執行緒私有資料。從程式執行來看,兩個執行緒對tsd的修改互不干擾。