Linux--线程安全--互斥与同步的实现、死锁

本文详细介绍了线程安全的概念及其实现方式,包括互斥锁的原理与使用方法、死锁的预防与处理策略,以及条件变量如何帮助实现同步控制。通过具体实例解释了这些概念的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 线程安全

  • 线程中对临界资源的访问操作是安全的
  • 临界资源:公共资源,大家都能访问到的资源

线程安全的实现

同步与互斥

  • 互斥:通过同一时间只有一个线程能够访问资源实现资源访问的安全性
  • 同步:通过条件判断让线程对临界资源访问更加合理有序

2. 互斥的实现

  • 互斥的实现:互斥锁(通过互斥锁保护线程对临界资源的访问操作不会被打断)
  • 本质:是一个只有0/1的计数器
  • 原理:标记临界资源的两种访问状态,可访问或者不可访问,在线程访问临界资源之前,先进行互斥锁加锁操作,(判断是都可访问,可访问则返回,不可访问则阻塞),在线程访问临界资源完毕后,进行解锁操作
  • 互斥锁本身计数器的操作是原子操作

操作流程以及接口认识

  1. 定义互斥锁变量:pthread_mutex_t mutex
  2. 初始化互斥锁:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    int pthread_mutex_init(pthread_mutex_t* mutex, pthread_mutextattr_t *attr)
  3. 在访问临界资源之前进行加锁
    int pthread_mutex_lock(pthread_mutex_t *mutex); --阻塞
    int pthread_mutex_trylock(pthread_mutex_t *mutex); --非阻塞
  4. 在访问临界资源完毕之后解锁
    int pthread_mutex_unlock(pthread_mutex_t *mutex);
  5. 不再使用互斥锁,则销毁
    int pthread_mutex_destroy(pthread_mutex_t *mutex);

黄牛抢票的例子:火车票有固定数量(计数器),四个黄牛进行抢票
int tickets=100; thread–黄牛(票数大于0,则抢票,没有票就退出)

在这里插入图片描述
在这里插入图片描述

3. 死锁

  • 描述的是程序因为流程无法继续推进卡死的情况

死锁产生的原因:死锁产生的四个必要条件:

  1. 互斥条件-- 同一时间只有一个线程能够访问资源
  2. 不可剥夺条件 --我的锁只能我解
  3. 请求与保持条件 --得到A锁然后请求B锁,请求不到B,不释放A
  4. 环路等待条件 --A线程拿到1锁,然后请求2锁,B拿到2请求1

预防死锁:预防四个必要条件的产生-- 破坏必要条件

  1. 保证加/解锁顺序一致
  2. 使用非阻塞加锁

避免死锁:银行家算法,死锁检测算法…

  • 银行家算法:所有资源表,已经分配资源表,当前请求资源表
    · 算法思想:将系统分为两种状态:安全/非安全,有可能出现风险的都属于非安全;是为了避免出现环路等待条件;
    · 银行家算法是避免死锁出现的一种算法,而不是预防的方法;
    · 处于不安全状态只是表示有风险,并不代表一定发生

死锁的处理方法

  • 鸵鸟策略、预防策略、避免策略、检测与接触死锁。

4. 同步的实现

  • 同步的实现:通过条件判断资源获取是否合理 --条件变量
  • 条件变量:一个pcb等待队列+使线程阻塞以及唤醒的接口
  • 原理:当线程获取资源不合理的时候,调用阻塞接口,使线程阻塞,将pcb挂到等待队列。等待资源访问合理的时候,通过唤醒接口唤醒阻塞的等待队列上的线程
  • 获取资源是否满足条件的判断本身就是临界资源的访问,需要加锁保护,条件变量需要搭配互斥锁一起使用
  • 注意:条件变量本身只提供阻塞与唤醒功能,而资源获取是否合理需要程序员自己判断完成

操作流程以及接口认识

  1. 定义条件变量:pthread_cond_t cond;
  2. 初始化条件变量:pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *attr);
  3. 在获取资源不合理时调用阻塞接口使线程阻塞
    int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);: 解锁,休眠,被唤醒后加锁
    int pthread_cond_timedwait(pathread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
  4. 其他线程促使资源获取合理后,唤醒等待队列上的线程
    int pthread_cond_signal(pthread_cond_t *cond);–至少唤醒一个
    int pthread_cond_broadcast(pthread_cond_t *cond);–唤醒所有
  5. 销毁:int pthread_cond_destroy(pthread_cond_t *cond);
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
//定义条件变量
pthread_cond_t cond;
//定义互斥变量
pthread_mutex_t mutex;
void *thr_entry(void* arg)
{
	while(1)
	{
		//阻塞
		pthread_cond_wait(&cond,&mutex);
		printf("I am a thread\n");
	}
	return NULL;
}
int main(int argc, char *argv[])
{
	pthread_t tid;
	//初始化互斥锁
	pthread_mutex_init(&mutex, NULL);
	//初始化条件变量
	pthread_cond_init(&cond, NULL);
	//创建
	int ret = pthread_create(&tid, NULL,thr_entry,NULL);
	if(ret != 0)
	{
		printf("thread create failed\n");
		return -1;
	}
	while(1)
	{
		//唤醒
		pthread_cond_signal(&cond);
		sleep(1);
	}
	//销毁
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	return0;
}

在这里插入图片描述

厨师顾客

  1. 顾客:加锁–>判断柜台上有没有饭,没有则阻塞(等有饭了吃) -->吃饭 -->(柜台没有饭)唤醒厨师做饭–>解锁
  2. 厨师:加锁–>判断柜台上有没有饭,有则阻塞(等没饭了做)–>做饭–>(柜台有饭)唤醒顾客吃饭–>解锁

注意事项:

  • 条件变量需要搭配互斥锁一起使用
  • 条件的判断应该使用while循环判断
    (三个顾客阻塞,有一碗饭,但是都被唤醒,开始加锁,只有一个顾客加锁成功,其他顾客卡在锁这里,等到这个顾客吃完饭解锁了,有可能获取到锁的不是厨师,而是卡在锁这里的顾客,这时候如果没有二次判断有没有饭,则可能就会出现在没有饭的情况下吃到饭)
  • 在具有多种角色的情况下,应该使用多个条件变量
    (三个顾客,因为没有饭,挂在阻塞队列上,一个厨师做好饭,唤醒一个顾客,顾客吃完唤醒等待队列上的pcb,但是因为队列上顾客在前,有可能唤醒的不是厨师,而是顾客,这个顾客二次判断因为没有饭再次陷入阻塞)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
//定义条件变量
pthread_cond_t cond_customer;
pthread_cond_t cond_cooker;
//定义互斥锁变量
pthread_mutex_t mutex;

int counter = 0;//0-没有饭; 1-有饭
void *cooker(void *arg)
{
    while(1) {
        //加锁
        pthread_mutex_lock(&mutex);
        while(counter == 1) {
            //阻塞
            pthread_cond_wait(&cond_cooker, &mutex);
        }
        //做饭
        printf("厨师做了一碗饭\n");
        counter++;
        //唤醒顾客吃饭
        pthread_cond_signal(&cond_customer);
        //解锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void *customer(void *arg)
{
    while(1) {
        //加锁
        pthread_mutex_lock(&mutex);
        while(counter == 0) {
            //阻塞
            pthread_cond_wait(&cond_customer, &mutex);
        }
        //吃饭
        printf("真好吃\n");
        counter--;
        //唤醒厨师做法
        pthread_cond_signal(&cond_cooker);
        //解锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
int main (int argc, char *argv[])
{
    pthread_t tid1, tid2;
    int ret;
	//初始化条件变量
    pthread_cond_init(&cond_customer, NULL);
    pthread_cond_init(&cond_cooker, NULL);
    //初始化互斥锁
    pthread_mutex_init(&mutex, NULL);
    for (int i = 0; i < 3; i++) {
        ret = pthread_create(&tid1, NULL, cooker, NULL);
        if (ret != 0) {
            printf("create thread error\n");
            return -1;
        }
    }
    for (int i = 0; i < 3; i++) {
        ret = pthread_create(&tid2, NULL, customer, NULL);
        if (ret != 0) {
            printf("create thread error\n");
            return -1;
        }
    }
    //等待
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    //销毁
    pthread_cond_destroy(&cond_cooker);
    pthread_cond_destroy(&cond_customer);
    pthread_mutex_destroy(&mutex);
    return 0;
}

在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值