Linux 线程同步、互斥锁、避免死锁、条件变量

2023-09-21 16:45:34

1. 线程同步概述

线程同步定义

线程同步,指的是控制多线程间的相对执行顺序,从而在线程间正确、有序地共享数据,以下为线程同步常见使用场合。

  • 多线程执行的任务在顺序上存在依赖关系
  • 线程间共享数据只能同时被一个线程使用

线程同步方法

在实际项目中,经常使用的线程同步方法主要分为三种:

  • 互斥锁
  • 条件变量
  • Posix信号量(包括有名信号量和无名信号量)

本节内容只介绍互斥锁和条件变量,Posix信号量后续在Posix IPC专题中介绍。

2. 互斥锁

互斥锁概念

互斥锁用于确保同一时间只有一个线程访问共享数据,使用方法为:

  • 加锁
  • 访问共享数据
  • 解锁

对互斥锁加锁后,任何其他试图再次对其加锁的线程都会被阻塞,直到当前线程释放该互斥锁,解锁时所有阻塞线程都会变成可运行状态,但究竟哪个先运行,这一点是不确定的。

互斥锁基本API

初始化与销毁

互斥锁是用pthread_mutex_t数据类型表示的,在使用互斥锁之前,需要先进行初始化,初始化方法有两种:

  • 设置为常量PTHREAD_MUTEX_INITIALIZER,只适用于静态分配的互斥锁
  • 调用pthread_mutex_init函数,静态分配和动态分配的互斥锁都可以

互斥锁使用完以后,可以调用pthread_mutex_destroy进行销毁,尤其是对于动态分配的互斥锁,在释放内存前,调用pthread_mutex_destroy是必须的。

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

//两个函数的返回值:成功返回0,失败返回错误编号
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

其中,pthread_mutex_init的第二个参数attr用于设置互斥锁的属性,如果要使用默认属性,只需把attr设为NULL。

上锁与解锁

//两个函数的返回值:成功返回0,失败返回错误编号
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

对互斥锁上锁,需要调用pthread_mutex_lock,如果互斥锁已经上锁,调用线程将阻塞到该互斥锁被释放。
对互斥锁解锁,需要调用pthread_mutex_unlock

两个特殊的上锁函数

尝试上锁

//成功返回0,失败返回错误编号
int pthread_mutex_trylock(pthread_mutex_t *mutex);

如果不希望调用线程阻塞,可以使用pthread_mutex_trylock尝试上锁:

  • 若mutex未上锁,pthread_mutex_trylock将加锁成功,返回0
  • 若mutex已上锁,pthread_mutex_trylock会加锁失败,返回EBUSY

限时上锁

//成功返回0,失败返回错误编号
int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *time);

pthread_mutex_timedlock是一个可以设置阻塞时间的上锁函数:

  • 当mutex已上锁时,调用线程会阻塞设定的时间
  • 当达到设定时间时,pthread_mutex_timedlock将加锁失败并解除阻塞,返回ETIMEDOUT

关于第二个参数time,有两点需要注意:

  • time表示等待的绝对时间,需要将其设为当前时间 + 等待时间
  • time是由struct timespec指定的,它由秒和纳秒来描述时间

示例代码

/*
 * 测试使用上述4个加锁函数
*/

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

pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_t mutex3;

void *thread1_start(void *arg)
{
    pthread_mutex_lock(&mutex1);
    printf("thread1 has locked mutex1\n");
    sleep(2); //保证thread2执行时mutex1还未解锁
    pthread_mutex_unlock(&mutex1);
}

void *thread2_start(void *arg)
{
    if (pthread_mutex_trylock(&mutex2) == 0)
        printf("thread2 trylock mutex2 sucess\n");

    if (pthread_mutex_trylock(&mutex1) == EBUSY)
        printf("thread2 trylock mutex1 failed\n");
          
    pthread_mutex_unlock(&mutex2);
}

void *thread3_start(void *arg)
{
    struct timespec time;
    struct tm *tmp_time;
    char s[64];
    int err;
    
    pthread_mutex_lock(&mutex3);
    printf("thread3 has locked mutex3\n");
    
    /*获取当前时间,并转化为本地时间打印*/
    clock_gettime(CLOCK_REALTIME, &time);
    tmp_time = localtime(&time.tv_sec);
    strftime(s, sizeof(s), "%r", tmp_time);
    printf("current time is %s\n", s);
    
    /*设置time = 当前时间 + 等待时间10S*/
    time.tv_sec = time.tv_sec + 10;
    
    /*mutex3已上锁,这里会阻塞*/
    if (pthread_mutex_timedlock(&mutex3, &time) == ETIMEDOUT)
        printf("pthread_mutex_timedlock mutex3 timeout\n");
    
    /*再次获取当前时间,并转化为本地时间打印*/
    clock_gettime(CLOCK_REALTIME, &time);
    tmp_time = localtime(&time.tv_sec);
    strftime(s, sizeof(s), "%r", tmp_time);
    printf("the time is now %s\n", s);  
        
    pthread_mutex_unlock(&mutex3);
}

int main()
{     
    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;
    
    /*测试pthread_mutex_lock和pthread_mutex_trylock*/
    pthread_mutex_init(&mutex1, NULL);
    pthread_mutex_init(&mutex2, NULL);
       
    pthread_create(&tid1, NULL, thread1_start, NULL);   
    pthread_create(&tid2, NULL, thread2_start, NULL);
    
    if (pthread_join(tid1, NULL) == 0)
    {
        pthread_mutex_destroy(&mutex1);
    }
    
    if (pthread_join(tid2, NULL) == 0)
    {
        pthread_mutex_destroy(&mutex2);
    }    
    
    /*测试pthread_mutex_timedlock*/
    pthread_mutex_init(&mutex3, NULL);
    pthread_create(&tid3, NULL, thread3_start, NULL);
      
    if (pthread_join(tid3, NULL) == 0)
    {
        pthread_mutex_destroy(&mutex3);
    }      
    
    return 0;
}

3. 避免死锁

线程的死锁概念

线程间死锁,指的是线程间相互等待临界资源而造成彼此无法继续执行的现象。

产生死锁的四个必要条件

  • 互斥条件:资源同时只能被一个线程使用,此时若有其他线程请求该资源,则请求线程必须等待
  • 不可剥夺条件:线程获得的资源在未使用完毕前,不能被其他线程抢夺,只能由获得该资源的线程主动释放
  • 请求与保持条件:线程已经至少得到了一个资源,但又提出了新的资源请求,而新的资源已被其他线程占有,此时请求线程被阻塞,但对自己已获得的资源保持不放
  • 循环等待条件:存在一个资源等待环,环中每一个线程都占有下一个线程所需的至少一个资源

直观上看,循环等待条件似乎和死锁的定义一样,其实不然,因为死锁定义中的要求更为严格:

  • 循环等待条件要求P(i+1)需要的资源,至少有一个来自P(i)即可
  • 死锁定义要求P(i+1)需要的资源,由且仅由P(i)提供

如何避免死锁

  • 所有线程以相同顺序加锁
  • 给所有的临界资源分配一个唯一的序号,对应的线程锁也分配同样的序号,系统中的所有线程按照严格递增的次序请求资源
  • 使用pthread_mutex_trylock尝试加锁,若失败就放弃上锁,同时释放已占有的锁
  • 使用pthread_mutex_timedlock限时加锁,若超时就放弃上锁,同时释放已占有的锁

4. 条件变量

条件变量概念

  • 条件变量是线程另一种可用的同步机制,它给多线程提供了一个回合的场所
  • 条件变量本身需要由互斥锁保护,线程在改变条件之前必须先上锁,其他线程在获得互斥锁之前不会知道条件发生了改变
  • 条件变量和互斥锁一起使用,可以使线程以无竞争的方式等待特定条件的发生

条件变量基本API

初始化与销毁

条件变量是用pthread_cond_t数据类型表示的,和互斥锁类似,条件变量的初始化方法也有两种:

  • 设置为常量PTHREAD_COND_INITIALIZER,只适用于静态分配的条件变量
  • 调用pthread_cond_init函数,适用于静态分配和动态分配的条件变量

条件变量使用完以后,可以调用pthread_cond_destroy进行销毁,同样的,如果是动态分配的条件变量,在释放内存前,该操作也是必须的。

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

//两个函数的返回值:成功返回0,失败返回错误编号
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cond);

其中,pthread_cond_init的第二个参数attr用于设置条件变量的属性,如果要使用默认属性,只需把attr设为NULL。

等待条件满足

//两个函数的返回值:成功返回0,失败返回错误编号
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *timeout);

可以调用pthread_cond_wait函数等待条件满足,使用步骤如下,传递给函数的互斥锁对条件进行保护,在条件满足之前,调用线程将一直阻塞。

  • 调用线程将锁住的互斥量传给pthread_cond_wait
  • pthread_cond_wait自动把调用线程放到等待条件的线程列表上,然后对互斥锁解锁
  • 当条件满足,pthread_cond_wait返回时,互斥锁再次被锁住
  • pthread_cond_wait返回后,调用线程再对互斥锁解锁

pthread_cond_timedwait是一个限时等待条件满足的函数,如果发生超时时条件还没满足,pthread_cond_timedwait将重新对互斥锁上锁,然后返回ETIMEDOUT错误。

注意:当条件满足从pthread_cond_wait和pthread_cond_timedwait返回时,调用线程必须重新计算条件,因为另一个线程可能已经在运行并改变了条件。

给线程发信号

有两个函数可以用于通知线程条件已经满足:

  • pthread_cond_signal至少能唤醒一个等待该条件的线程
  • pthread_cond_broadcast可以唤醒等待该条件的所有线程
//两个函数的返回值:成功返回0,失败返回错误编号
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

在调用上面两个函数时,我们说这是在给线程发信号,注意,一定要先获取互斥锁,再改变条件,然后给线程发信号,最后再对互斥锁解锁。

示例代码

/*
 * 结合使用条件变量和互斥锁进行线程同步
*/

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

static pthread_cond_t  cond;
static pthread_mutex_t mutex;
static int             cond_value;
static int             quit;

void *thread_signal(void *arg)
{
    while (!quit)
    {
        pthread_mutex_lock(&mutex);
        cond_value++;                //改变条件,使条件满足
        pthread_cond_signal(&cond);  //给线程发信号 
        printf("signal send, cond_value: %d\n", cond_value);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }    
}

void *thread_wait(void *arg)
{
    while (!quit)
    {
        pthread_mutex_lock(&mutex);
        
        /*通过while (cond is true)来保证从pthread_cond_wait成功返回时,调用线程会重新检查条件*/
        while (cond_value == 0)
            pthread_cond_wait(&cond, &mutex);
            
        cond_value--;
        printf("signal recv, cond_value: %d\n", cond_value);
        
        pthread_mutex_unlock(&mutex);
        sleep(1);
    } 
}

int main()
{     
    pthread_t tid1;
    pthread_t tid2;
    
    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);
       
    pthread_create(&tid1, NULL, thread_signal, NULL);   
    pthread_create(&tid2, NULL, thread_wait, NULL);
    
    sleep(5);
    quit = 1;
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
      
    return 0;
}

转载至:https://zhuanlan.zhihu.com/p/633169684

更多推荐

【无标题】

想自学网络安全(黑客技术)首先你得了解什么是网络安全!什么是黑客网络安全可以基于攻击和防御视角来分类,我们经常听到的“红队”、“渗透测试”等就是研究攻击技术,而“蓝队”、“安全运营”、“安全运维”则研究防御技术。无论网络、Web、移动、桌面、云等哪个领域,都有攻与防两面性,例如Web安全技术,既有Web渗透,也有Web

1.6python基础语法——输出

作用:程序输出内容给用户1)格式化符号格式符号转换%s字符串%d有符号的十进制整数%f浮点数%c字符%u无符号十进制整数%o八进制整数%x十六进制整数(小写ox)%X十六进制整数(大写OX)%e科学计数法(小写’e’)%E科学计数法(大写’E’)%g%f和%e的简写%G%f和%E的简写技巧%06d,表示输出的整数显示位

十、阶段实践练习

阶段实践练习1.阶段实践练习1.1.练习1~~~~象棋口诀1.2.练习2~~~~输出汇款单1.3.练习3~~~~输出个人信息1.4.练习4~~~~计算月收入1.5.练习5~~~~计算商和余数1.6.练习6~~~~判断成绩能否及格1.7.练习7~~~~话费充值1.8.练习8~~~~货车装西瓜———————————————

2023-09-21 事业-代号z-个人品牌-对事务并发控制理论的精通-缺陷-分析

摘要:对于数据库内核专家来说,对于事务并发控制的理论的精通是必备的,但是最近这段时间,我能明显到理论和现实的割裂性,这种情况不但对于理论的驾驭存在挑战,将理论推行到实践也面临挑战.本文对此种情况做一些分析.上下文相关:2023-09-20事业-代号z-个人品牌-数据库内核专家-分析_财阀悟世的博客-CSDN博客需要直接

第七天:gec6818开发板QT和Ubuntu中QT安装连接sqlite3数据库驱动环境保姆教程

sqlite3数据库简介帮助文档SQLProgramming大多数关系型数的操作步骤:1)连接数据库多数关系型数据库都是C/S模型(Client/Server)sqlite3是一个本地的单文件关系型数据库,同样也有“连接”的过程2)操作数据库作为程序员,对数据库最常见的操作就是增删改查3)关闭数据库连接也是一种资源,用

差分数组leetcode 2770 数组的最大美丽值

什么是差分数组差分数组是一种数据结构,它存储的是一个数组每个相邻元素的差值。换句话说,给定一个数组arr[],其对应的差分数组diff[]将满足:diff[i]=arr[i+1]-arr[i]对于所有0<=i<n-1差分数组的作用用于高效地实现某些特定的数组操作,如对某一范围的数组元素全部增加或减少一个固定值。例如,考

Jenkins学习笔记5

[root@localhost~]#cd/var/lib/jenkins/workspace/nginx_root_sync[root@localhostnginx_root_sync]#lltotal16-rw-r--r--1jenkinsjenkins6Sep2020:571.php-rw-r--r--1jenki

C++项目:仿mudou库实现高性能高并发服务器

文章目录一、实现目标二、前置知识(一)HTTP服务器1.概念2.Reactor模型:3.分类一、实现目标仿muduo库OneThreadOneLoop式主从Reactor模型实现高并发服务器:通过咱们实现的高并发服务器组件,可以简洁快速的完成⼀个高性能的服务器搭建。并且,通过组件内提供的不同应⽤层协议支持,也可以快速完

代码配置仓库GitLab安装部署

Github是目前世界上代码行数最多的在线软件版本配置库平台,而Gitlab是Github对应的开源版本,本文主要描述Gitlab的安装部署。https://about.gitlab.com/https://gitlab.cn/install/如上所示,从官方网站中下载不同操作系统的版本,本文主要描述Centos的安装

UML类图

优质博客:IT-BLOG-CNUML(UnidiedModelingLanguage)统一建模语言:用来设计软件的可视化建模语言,能够表达软件设计中的动态与静态信息。UML定义了用例图、类图、对象图、状态图、活动图、时序图、协作图、构件图、部署图等9种图。IDEA展示类图及类图关系【1】选中.java或者编辑的.jav

部署Kafka

kafka:kafka_2.13-3.5.1NOTE:YourlocalenvironmentmusthaveJava8+installed.ApacheKafkacanbestartedusingZooKeeperorKRaft.Togetstartedwitheitherconfigurationfollowone

热文推荐