Linux 多线程应用编程 pthread_key_create
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_key_t key;
struct for_test {
int i;
float k;
};
void *thread1 (void *arg)
{
struct for_test data;
data.i = 1;
data.k = 1.23;
pthread_setspecific (key, &data);
printf ("struct_data的地址为 0x%p\n", &(data));
printf ("thread1 pthread_getspecific(key)返回的地址为:0x%p\n", (struct for_test *)pthread_getspecific(key));
printf ("thread1 第一次利用 pthread_getspecific(key)打印线程中与key关联的结构体中成员值:\ndata.i:%d\ndata.k: %f\n", ((struct for_test*)pthread_getspecific (key))->i, ((struct for_test *)pthread_getspecific(key))->k);
sleep(2);
printf ("\n\nthread1 第二次利用 pthread_getspecific(key)打印线程中与key关联的结构体中成员值:\ndata.i:%d\ndata.k: %f\n", ((struct for_test*)pthread_getspecific (key))->i, ((struct for_test *)pthread_getspecific(key))->k);
}
void *thread2 (void *arg)
{
int num = 10;
sleep (1);
printf ("\n\nthread2 变量 num 的地址为 0x%p\n", &num);
pthread_setspecific (key, &num);
printf ("thread2 pthread_getspecific(key)返回的地址为:0x%p\n", (int *)pthread_getspecific(key));
printf ("thread2 利用 pthread_getspecific(key)打印线程中与key关联的整型变量temp 值:%d, k = %f\n", *((int *)pthread_getspecific(key)), ((struct for_test *)pthread_getspecific(key))->k);
}
int main (void)
{
pthread_t tid1, tid2;
pthread_key_create (&key, NULL);
pthread_create (&tid1, NULL, (void *)thread1, NULL);
pthread_create (&tid2, NULL, (void *)thread2, NULL);
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
pthread_key_delete (key);
return 0;
}