函数应用背景:在单线程程序中,函数经常使用全局变量或静态变量,这是不会影响程序的正确性的,但如果线程调用的函数使用全局变量或静态变量,则很可能引起编程错误,因为这些函数使用的全局变量和静态变量无法为不同的线程保存各自的值,而当同一进程内的不同线程几乎同时调用这样的函数时就可能会有问题发生。而解决这一问题的一种方式就是使用线程特定数据的机制。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
#define NUM 2
int g_key_size = 10;
static pthread_key_t msg_key;
static void msg_key_destructor(void* p)
{
free(p);
}
void* get_msg_key()
{
int status;
void* key;
if ((key = pthread_getspecific(msg_key)) == NULL) {
key = malloc(g_key_size);
if (key == NULL){
printf("10, %d\n", errno);
abort();
}
status = pthread_setspecific(msg_key, key);
if (status != 0){
printf("20 %d\n", status);
abort();
}
}
return key;
}
void *write_main(void *arg)
{
int *key = NULL;
while(1){
key = get_msg_key();
*key = pthread_self();
printf("%d:%d\n", pthread_self(), *key);
if(pthread_self() != *key)
printf("no\n");
}
}
main()
{
int stat;
pthread_t pth[NUM];
int i;
printf("start\n");
stat = pthread_key_create(&msg_key, msg_key_destructor);
if (stat != 0) {
return stat;
}
for(i=0; i<NUM; i++){
stat = pthread_create(&pth[i], NULL, write_main, NULL);
if(stat != 0)
return errno;
}
for(i=0; i<NUM; i++)
pthread_join(pth[i], NULL);
printf("over\n");
}