linux 互斥锁

多条线程对同一个变量操作,有可能会同时修改了这个变量的值,导致线程不安全
如下线程就是不安全的

这3条线程都对a进程操作,如果t1线程把a减到了0,那么下一次进入while(0>0)就不满足,但是有可能其他线程在t1线程执行了a-- 使得a=0的时候切换了,进入了运行态,并且它又是刚好运行切换的点是a–,那么a会变成-1,这就导致线程不安全了。所以需要有一个保护机制,保护a变量被线程操作的时候,不能发生任务切换,就需要加锁。

不安全线程

#include <stdio.h>
#include <pthread.h>

int a=100;
void sub()
{

    while (a>0)
    {
        a--;
     printf("sub %d\n",a);
    }

}



int main(int argc, char **argv)
{
    pthread_t t1,t2,t3;
  
    pthread_create(&t1,NULL,sub,NULL);
    pthread_create(&t2,NULL,sub,NULL);
    pthread_create(&t3,NULL,sub,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    while(1);
    return 0;
}

没有互斥锁运行程序

#include <stdio.h>
#include <pthread.h>

int a=100;
void sub()
{

    while (a>0)
    {
        a--;
     printf("sub %d\n",a);
    }

}



int main(int argc, char **argv)
{
    pthread_t t1,t2,t3;
  
    pthread_create(&t1,NULL,sub,NULL);
    pthread_create(&t2,NULL,sub,NULL);
    pthread_create(&t3,NULL,sub,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    while(1);
    return 0;
}

这可以看出a的值出输出不是按顺序减少,因为存在多个线程在做减法。
在这里插入图片描述

添加互斥锁

1、pthread_mutex_t lock; 定义互斥锁

2、 pthread_mutex_init(&lock,NULL);//初始化锁

3、pthread_mutex_lock( &lock ) ; 在需要保护代码段上锁

4、 pthread_mutex_unlock( &lock ) ; 解锁

5、pthread_mutex_destroy(&lock); 销毁锁

有互斥锁

#include <stdio.h>
#include <pthread.h>

int a=100;
pthread_mutex_t lock;
void sub()
{
 pthread_mutex_lock( &lock ) ;
    while (a>0)
    {
        a--;
     printf("sub %d\n",a);
    }
 pthread_mutex_unlock( &lock ) ;
}



int main(int argc, char **argv)
{
    pthread_t t1,t2,t3;
     pthread_mutex_init(&lock,NULL);//初始化锁
    pthread_create(&t1,NULL,sub,NULL);
    pthread_create(&t2,NULL,sub,NULL);
    pthread_create(&t3,NULL,sub,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    while(1);
    pthread_mutex_destroy(&lock);
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值