linux 線程私有數據

  • 類似於errno,不是全局變量,因爲多個線程同時訪問的話可能出現資源同步問題,私有數據是一鍵對多值,每個線程可以根據同一個key,設置自己的數據,也可以通過key對數據進行獲取
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_key_t key;

struct student{
    int id;
    char nm[20];
}student_def;

void child1(void* arg)
{
    struct student stu_tmp;
    memset(&stu_tmp, 0x00, sizeof(student_def));
    stu_tmp.id=10;
    strcpy(stu_tmp.nm, "hello");
    pthread_setspecific(key, (void*)&stu_tmp);
    printf("child1:id=%d, nm=%s\n", ((struct student*)pthread_getspecific(key))->id, 
                        ((struct student*)pthread_getspecific(key))->nm);
}

void child2(void* arg)
{
    struct student stu_tmp;
    memset(&stu_tmp, 0x00, sizeof(student_def));
    stu_tmp.id=20;
    strcpy(stu_tmp.nm, "world");
    pthread_setspecific(key, (void*)&stu_tmp);
    
    printf("child2:id=%d, nm=%s\n", ((struct student*)pthread_getspecific(key))->id, 
                        ((struct student*)pthread_getspecific(key))->nm);
}

int main()
{
    pthread_t ptid1;
    pthread_t ptid2;
    
    pthread_key_create(&key, NULL);
    pthread_create(&ptid1, NULL, (void*)child1, NULL);
    pthread_create(&ptid2, NULL, (void*)child2, NULL);
    
    pthread_join(ptid1, NULL);
    pthread_join(ptid2, NULL);
    pthread_key_delete (key);

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章