linux线程安全浅析

在《深入理解计算机系统》一书中。

线程不安全函数分为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类。调用线程不安全的函数


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值