在《深入理解计算机系统》一书中。
线程不安全函数分为4类
第1类:不保护共享变量的函数
第2类:保持跨越多个调用状态的函数
第3类:返回指向静态变量的指针的函数
现在对第3类写了一个测试程序:
void*thread(void*vargp)
{static int static_value=0;
int ID=(int)(vargp);
printf("the threadID:%d,the value of i:%d\n",ID,++static_value);
return &static_value;
//return NULL;
}
int main(int argc,char**argv)
{
pthread_t tid1,tid2;
int ID1=1;
int ID2=2;
int *value1;
int *value2;
Pthread_create(&tid1,NULL,thread,(int*)ID1);
Pthread_create(&tid2,NULL,thread,(int*)ID2);
Pthread_join(tid1,&value1);
Pthread_join(tid2,&value2);
printf("thread1 returns %d\n",*value1);
printf("thread2 returns %d\n",*value2);
return 0;
}
测试结果为:
the threadID:1,the value of i:1
the threadID:2,the value of i:2
thread1 returns 2
thread2 returns 2
返回的值于其实际值不一致。因为正在被线程使用的结果被另一个线程悄悄覆盖了。
所以需要使用加锁拷贝技术。
第4类。调用线程不安全的函数