背景
#include <stdio.h>
#include <pthread.h>
int global_sum = 0;
void * mul_add(void *arges)
{
for(int i=0; i<100; i++)
{
global_sum += 1;
}
return 0;
}
int main()
{
pthread_t t1;
pthread_t t2;
pthread_create(&t1, NULL, mul_add, NULL);
pthread_create(&t2, NULL, mul_add, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
上面的代码中global_sum的值时候到两个线程影响的。有时候希望,同一个函数访问一个各个线程自己的全局变量,而不用为每个线程单独定义一个全局变量。这个时候pthread_key就很好地解决了这个问题。
api
pthread_key_create,pthread_setspecific,pthread_getspecific
#include <stdio.h>
#include <pthread.h>
#include <malloc.h>
pthread_key_t global_sum_key;
void mul_add()
{
int * global_sum = (int *)pthread_getspecific(global_sum_key);
for(int i=0; i<100; i++)
{
*global_sum += 1;
}
printf("global_sum:%d!\n", *global_sum);
}
void * mul_fun(void * args)
{
void * global_sum = calloc(1, sizeof(int));
pthread_setspecific(global_sum_key, global_sum);
mul_add();
return NULL;
}
void global_sum_free(void * des)
{
free(des);
}
int main()
{
pthread_t t1;
pthread_t t2;
pthread_key_create(&global_sum_key, global_sum_free);
pthread_create(&t1, NULL, mul_fun, NULL);
pthread_create(&t2, NULL, mul_fun, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
上面的代码两个线程都打印了100。证明了各自的global_sum_key空间里面的值是不受影响的。这样子就好像函数都用global_sum_key这个全局变量,但是这个全局变量是各自线程独立的。