Linux下多线程的线程保护

目录

 

一 开发环境

二 互斥锁


一 开发环境

系统:Ubuntu16.04

线程库:pthread

语言:c/c++

Linux下的线程保护,最常用的是互斥锁、条件变量、信号量和读写锁。

先来试一下互斥锁吧

二 互斥锁

多线程之间可能需要互斥的访问一些全局变量,这就需要互斥的来访问,这些需要共享访问的字段被称作是临界资源,访问临界资源的程序段称作是临界区
实现线程间的互斥与同步机制的是锁机制,下面是常用的锁机制的函数和类。

  1. pthread_mutex_t mutex 锁对象
  2. pthread_mutex_init(&mutex,NULL) 在主线程中初始化锁为解锁状态
  3. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER 编译时初始化锁为解锁状态
  4. pthread_mutex_lock(&mutex)(阻塞加锁)访问临界区加锁操作
  5.  pthread_mutex_trylock( &mutex)(非阻塞加锁); pthread_mutex_lock() 类似,不同的是在锁已经被占据时返回 EBUSY 而不是挂起等待。
  6. pthread_mutex_unlock(&mutex): 访问临界区解锁操作

示例代码: 

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
 
int num = 0;
void thread_num(void);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
 
int main()
{
  int ret;
  pthread_t thread1,thread2,thread3;
  
  ret = pthread_create(&thread1,NULL,(void *)&thread_num,NULL);
  ret = pthread_create(&thread2,NULL,(void *)&thread_num,NULL);
  ret = pthread_create(&thread3,NULL,(void *)&thread_num,NULL);
 
  pthread_join(thread1,NULL);
  pthread_join(thread2,NULL);
  pthread_join(thread3,NULL);
 
  return 0;
}
 
void thread_num(void)
{

  for(int i=0;i<3;++i)
  {
    if(pthread_mutex_lock(&mutex) != 0)
    {
      perror("pthread_mutex_lock");
    }
    num++;
    printf("%u:num=%d\n",pthread_self(),num);
    if(pthread_mutex_unlock(&mutex) != 0)
    {
      perror("pthread_mutex_unlock");
    }
    sleep(1);
  }
}

运行结果:

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值