关于互斥锁

顾名思义,在多线程下,用来锁定资源使用权限。

我们先看一段代码:

#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>

int count =0;
void *func(void* argc)
{
  for(int i=0; i<3; i++)
  {
    printf("[before] tid:%d count:%d\n", pthread_self(), count);
count++; printf("[after] tid:%d count:%d\n", pthread_self(), count); }


  pthread_exit(NULL);
  return NULL; 
}

int main()
{
  pthread_t t1,t2;
  pthread_create(&t1, NULL, func, NULL);
  pthread_create(&t2, NULL, func, NULL);

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  return 0;
}

t1 t2两个线程可以同时修改count,所以很难得到我们希望的结果。

[before] tid:1845761792 count:0

[after] tid:1845761792 count:1

[before] tid:1845761792 count:1

[after] tid:1845761792 count:2

[before] tid:1845761792 count:2

[before] tid:1837369088 count:0

[after] tid:1837369088 count:4

[before] tid:1837369088 count:4

[after] tid:1837369088 count:5

[before] tid:1837369088 count:5

[after] tid:1837369088 count:6

[after] tid:1845761792 count:3


如果希望一个线程在修改资源时,其他线程无法获取资源的修改权时,可以使用互斥锁来实现。

修改一下代码:

#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>

int count =0;
pthread_mutex_t mutex;
 
void *func(void* argc)
{
  for(int i=0; i<3; i++)
  {
    pthread_mutex_lock(&mutex); 
    printf("[before] tid:%d count:%d\n", pthread_self(), count);
    count++;
    printf("[after] tid:%d count:%d\n", pthread_self(), count);
    pthread_mutex_unlock(&mutex); 
  }
  pthread_exit(NULL);
  return NULL; 
}

int main()
{
  pthread_mutex_init(&mutex, NULL); // 初始化互斥锁 
  pthread_t t1,t2;
  pthread_create(&t1, NULL, func, NULL);
  pthread_create(&t2, NULL, func, NULL);

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  return 0;
}

结果:

[before] tid:806139648 count:0

[after] tid:806139648 count:1

[before] tid:806139648 count:1

[after] tid:806139648 count:2

[before] tid:806139648 count:2

[after] tid:806139648 count:3

[before] tid:797746944 count:3

[after] tid:797746944 count:4

[before] tid:797746944 count:4

[after] tid:797746944 count:5

[before] tid:797746944 count:5

[after] tid:797746944 count:6





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值