Linux系统编程(十二)线程同步、锁、条件变量、信号量

news2024/10/6 8:33:22

线程同步:

协同步调,对公共区域数据按序访问。防止数据混乱,产生与时间有关的错误。

数据混乱的原因

数据混乱的原因

一、互斥锁/互斥量mutex

线程同步和锁

1. 建议锁(协同锁):

公共数据进行保护。所有线程【应该】在访问公共数据前先拿锁再访问。但,锁本身不具备强制性。

建议锁

2. 互斥锁的使用步骤:

互斥锁的使用步骤

初始化互斥量:

	pthread_mutex_t mutex;

	1. pthread_mutex_init(&mutex, NULL);   			动态初始化。

	2. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;	静态初始化。

restrict关键字:

用来限定指针变量。被该关键字限定的指针变量所指向的内存操作,只能由本指针完成。

3. 使用锁的注意事项:

尽量保证锁的粒度, 越小越好。(访问共享数据前,加锁。访问结束【立即】解锁。)

互斥锁,本质是结构体。 可以看成整数。 初始化时值为 1。(pthread_mutex_init() 函数调用成功。)

	lock加锁: --操作, 阻塞线程。

	unlock解锁: ++操作, 换醒阻塞在锁上的线程。

	try锁:尝试加锁,成功--。失败直接返回,同时设置错误号 EBUSY,不阻塞。

4. 死锁:

是使用锁不恰当导致的现象:

	1. 线程视图对同一个互斥量A加锁两次。

	2. 线程1拥有A锁,请求获得B锁;线程2拥有B锁,请求获得A锁。

死锁

示例:访问共享数据(stdout)
//pthrd_shared.c
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex;

void *tfn(void *arg)
{
    srand(time(NULL));

    while (1) {
        pthread_mutex_lock(&mutex);
        printf("hello ");
        sleep(rand() % 3);	/*模拟长时间操作共享资源,导致cpu易主,产生与时间有关的错误*/
        printf("world\n");
        pthread_mutex_unlock(&mutex);
        sleep(rand() % 3);//保证锁的粒度越小越好,(访问结束立即解锁)
    }

    return NULL;
}

int main(void)
{
    pthread_t tid;
    srand(time(NULL));
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid, NULL, tfn, NULL);
    while (1) {

        pthread_mutex_lock(&mutex);
        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        pthread_mutex_unlock(&mutex);
        sleep(rand() % 3);

    }
    pthread_join(tid, NULL);
    pthread_mutex_destroy(&mutex);

    return 0;
}

二、读写锁:

  • 锁只有一把。以读方式给数据加锁——读锁。以写方式给数据加锁——写锁。

  • 读共享,写独占。

  • 写锁优先级高。

  • 相较于互斥量而言,当读线程多的时候,提高访问效率

读写锁原理

读写锁特性

pthread_rwlock_t  rwlock;类型

pthread_rwlock_init(&rwlock, NULL);

pthread_rwlock_rdlock(&rwlock);		

pthread_rwlock_wrlock(&rwlock);		

pthread_rwlock_tryrdlock(&rwlock);		

pthread_rwlock_trywrlock(&rwlock);		

pthread_rwlock_unlock(&rwlock);

pthread_rwlock_destroy(&rwlock);

示例:3个线程不定时 “写” 全局资源,5个线程不定时 “读” 同一全局资源

//rwlock.c
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int counter;                          //全局资源
pthread_rwlock_t rwlock;

void *th_write(void *arg)
{
    int t;
    int i = (int)arg;

    while (1) {
        t = counter;                    // 保存写之前的值
        usleep(1000);

        pthread_rwlock_wrlock(&rwlock);
        printf("=======write %d: %lu: counter=%d ++counter=%d\n", i, pthread_self(), t, ++counter);
        pthread_rwlock_unlock(&rwlock);

        usleep(9000);               // 给 r 锁提供机会
    }
    return NULL;
}

void *th_read(void *arg)
{
    int i = (int)arg;

    while (1) {
        pthread_rwlock_rdlock(&rwlock);
        printf("----------------------------read %d: %lu: %d\n", i, pthread_self(), counter);
        pthread_rwlock_unlock(&rwlock);

        usleep(2000);                // 给写锁提供机会
    }
    return NULL;
}

int main(void)
{
    int i;
    pthread_t tid[8];

    pthread_rwlock_init(&rwlock, NULL);

    for (i = 0; i < 3; i++)
        pthread_create(&tid[i], NULL, th_write, (void *)i);

    for (i = 0; i < 5; i++)
        pthread_create(&tid[i+3], NULL, th_read, (void *)i);

    for (i = 0; i < 8; i++)
        pthread_join(tid[i], NULL);

    pthread_rwlock_destroy(&rwlock);            //释放读写琐

    return 0;
}

三、条件变量:

本身不是锁! 但是通常结合锁来使用。 mutex

pthread_cond_wait函数

pthread_cond_t cond;//类型

初始化条件变量:

	1. pthread_cond_init(&cond, NULL);   			动态初始化。

	2. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;	静态初始化。

阻塞等待条件:

	3. pthread_cond_wait(&cond, &mutex);

	作用:	1) 阻塞等待条件变量满足

		2) 解锁已经加锁成功的信号量 (相当于 pthread_mutex_unlock(&mutex))
		
	注:1和2两步为一个原子操作

		3)  当条件满足,函数返回时,重新加锁信号量 (相当于, pthread_mutex_lock(&mutex);)

	4. pthread_cond_timedwait():可设置超时

5. pthread_cond_signal(): 唤醒阻塞在条件变量上的 (至少)一个线程。

6. pthread_cond_broadcast(): 唤醒阻塞在条件变量上的 所有线程。

7. pthread_cond_destroy(&cond):销毁条件变量

示例:使用条件变量完成生产者、多个消费者模型

条件变量-生产者/消费者模型

//借助条件变量模拟 生产者-消费者问题
//pthread_cond_produce_consumer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

void err_thread(int ret, char *str)
{
    if (ret != 0) {
        fprintf(stderr, "%s:%s\n", str, strerror(ret));
        pthread_exit(NULL);
    }
}

struct msg {
    int num;
    struct msg *next;
};

struct msg *head;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;      // 定义/初始化一个互斥量
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER;      // 定义/初始化一个条件变量

void *produser(void *arg)
{
    while (1) {
        struct msg *mp = malloc(sizeof(struct msg));

        mp->num = rand() % 1000 + 1;                        // 模拟生产一个数据`
        printf("--produce %d\n", mp->num);

        pthread_mutex_lock(&mutex);                         // 加锁 互斥量
        mp->next = head;                                    // 写公共区域
        head = mp;
        pthread_mutex_unlock(&mutex);                       // 解锁 互斥量

        pthread_cond_signal(&has_data);                     // 唤醒阻塞在条件变量 has_data上的线程.

        sleep(rand() % 3);
    }

    return NULL;
}

void *consumer(void *arg)
{
    while (1) {
        struct msg *mp;

        pthread_mutex_lock(&mutex);                         // 加锁 互斥量
        while (head == NULL) {															// 注:多个消费者,这里需要使用while,不能使用if
            pthread_cond_wait(&has_data, &mutex);           // 阻塞等待条件变量, 解锁
        }                                                   // pthread_cond_wait 返回时, 重新加锁 mutex

        mp = head;																					//读公共区域
        head = mp->next;

        pthread_mutex_unlock(&mutex);                       // 解锁 互斥量
        printf("---------consumer id: %lu :%d\n", pthread_self(), mp->num);

        free(mp);
        sleep(rand()%3);
    }

    return NULL;
}

int main(int argc, char *argv[])
{
    int ret;
    pthread_t pid, cid;

    srand(time(NULL));

    ret = pthread_create(&pid, NULL, produser, NULL);           // 生产者
    if (ret != 0) 
        err_thread(ret, "pthread_create produser error");

    ret = pthread_create(&cid, NULL, consumer, NULL);           // 消费者
    if (ret != 0) 
        err_thread(ret, "pthread_create consuer error");
    ret = pthread_create(&cid, NULL, consumer, NULL);           // 消费者
    if (ret != 0) 
        err_thread(ret, "pthread_create consuer error");
    ret = pthread_create(&cid, NULL, consumer, NULL);           // 消费者
    if (ret != 0) 
        err_thread(ret, "pthread_create consuer error");

    pthread_join(pid, NULL);
    pthread_join(cid, NULL);

    return 0;
}

四、信号量:

  • 应用于线程、进程间同步(既能保证同步,数据不混乱,又能提高线程并发)。

  • 相当于 初始化值为 N 的互斥量。 N值,表示可以同时访问共享数据区的线程数。

信号量函数

sem_t sem;	定义类型。

int sem_init(sem_t *sem, int pshared, unsigned int value);

参数:
	sem: 信号量 

	pshared:	0: 用于线程间同步
			
			1: 用于进程间同步

	value:N值。(指定同时访问的线程数)

sem_destroy();

sem_wait();		一次调用,做一次-- 操作, 当信号量的值为 0 时,再次 -- 就会阻塞。 (对比 pthread_mutex_lock)

sem_post();		一次调用,做一次++ 操作. 当信号量的值为 N 时, 再次 ++ 就会阻塞。(对比 pthread_mutex_unlock)

sem_timewait(sem_t *sem, const struct timespec* abs_timeout);
	
		//abs_timeout 采用的是绝对时间。
		
	定时1秒:
	
		time_t cur = time(NULL);获取当前时间(相对时间)

		struct timespec t;定义timespec结构体变量t
		
		t.tv_sec = cur + 1;定时1秒
		
		t.tv_nsec = t.tv_sec+100;
	
		sem_timedwait(&sem, &t);传参

示例:使用信号量实现生产者、消费者模型

信号量-生产者消费者模型

//sem_product_consumer.c
/*信号量实现 生产者 消费者问题*/

#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>

#define NUM 5               

int queue[NUM];                                     //全局数组实现环形队列
sem_t blank_number, product_number;                 //空格子信号量, 产品信号量

void *producer(void *arg)
{
    int i = 0;

    while (1) {
        sem_wait(&blank_number);                    //生产者将空格子数--,为0则阻塞等待
        queue[i] = rand() % 1000 + 1;               //生产一个产品
        printf("----Produce---%d\n", queue[i]);        
        sem_post(&product_number);                  //将产品数++

        i = (i+1) % NUM;                            //借助下标实现环形
        sleep(rand()%1);
    }
}

void *consumer(void *arg)
{
    int i = 0;

    while (1) {
        sem_wait(&product_number);                  //消费者将产品数--,为0则阻塞等待
        printf("-Consume---%d\n", queue[i]);
        queue[i] = 0;                               //消费一个产品 
        sem_post(&blank_number);                    //消费掉以后,将空格子数++

        i = (i+1) % NUM;
        sleep(rand()%3);
    }
}

int main(int argc, char *argv[])
{
    pthread_t pid, cid;

    sem_init(&blank_number, 0, NUM);                //初始化空格子信号量为5, 线程间共享 -- 0
    sem_init(&product_number, 0, 0);                //产品数为0

    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);

    pthread_join(pid, NULL);
    pthread_join(cid, NULL);

    sem_destroy(&blank_number);
    sem_destroy(&product_number);

    return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1807178.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Vue3 + TS + Antd + Pinia 从零搭建后台系统(一) 脚手架搭建 + 入口配置

简易后台系统搭建开启&#xff0c;分几篇文章更新&#xff0c;本篇主要先搭架子&#xff0c;配置入口文件等目录 效果图一、搭建脚手架&#xff1a;二、处理package.json基础需要的依赖及运行脚本三、创建环境运行文件四、填充vue.config.ts配置文件五、配置vite-env.d.ts使项目…

微服务开发与实战Day04 - 网关路由和配置

一、网关路由 网关&#xff1a;就是网络的关口&#xff0c;负责请求的路由、转发、身份校验。 在SpringCloud中网关的实现包括两种&#xff1a; 1. 快速入门 Spring Cloud Gateway 步骤&#xff1a; ①新建hm-gateway模块 ②引入依赖pom.xml(hm-gateway) <?xml version…

【python】OpenCV GUI——Trackbar(14.2)

学习来自 OpenCV基础&#xff08;12&#xff09;OpenCV GUI中的鼠标和滑动条 文章目录 GUI 滑条介绍cv2.createTrackbar 介绍牛刀小试 GUI 滑条介绍 GUI滑动条是一种直观且快速的调节控件&#xff0c;主要用于改变一个数值或相对值。以下是关于GUI滑动条的详细介绍&#xff1a…

course-nlp——6-rnn-english-numbers

本文参考自https://github.com/fastai/course-nlp。 使用 RNN 预测数字的英文单词版本 在上一课中&#xff0c;我们将 RNN 用作语言模型的一部分。今天&#xff0c;我们将深入了解 RNN 是什么以及它们如何工作。我们将使用尝试预测数字的英文单词版本的问题来实现这一点。 让…

Llama模型家族之Stanford NLP ReFT源代码探索 (三)reft_model.py代码解析

LlaMA 3 系列博客 基于 LlaMA 3 LangGraph 在windows本地部署大模型 &#xff08;一&#xff09; 基于 LlaMA 3 LangGraph 在windows本地部署大模型 &#xff08;二&#xff09; 基于 LlaMA 3 LangGraph 在windows本地部署大模型 &#xff08;三&#xff09; 基于 LlaMA…

C# WPF入门学习主线篇(十七)—— UniformGrid布局容器

C# WPF入门学习主线篇&#xff08;十七&#xff09;—— UniformGrid布局容器 欢迎来到C# WPF入门学习系列的第十七篇。在前几篇文章中&#xff0c;我们已经探讨了 Canvas、StackPanel、WrapPanel、DockPanel 和 Grid 布局容器及其使用方法。本篇博客将介绍另一种非常实用且简单…

推荐三款你不知道的良心软件

Tico——抠图、拼图软件 抠图软件大家见过很多了把&#xff0c;但是从多张图片中抠出来的图片拼接成一张图片你们很少见过吧。 Tico就是一款将抠出来的图片拼接成一张新图片的软件&#xff0c;目前仅支持IOS平台。 Tico拼贴图提供了强大的图像编辑和处理功能&#xff0c;用户…

预期值与实际值对比

编辑实际值和预期值变量 因为在单独的代码当中&#xff0c;我们先定义了变量str&#xff0c;所以在matcher时传入str参数&#xff0c;但当我们要把这串代码写在testrun当中&#xff0c;改下传入的参数&#xff0c;与excel表做连接 匹配的结果是excel表中的expect结果&#xf…

整型变量、赋值语句、cin 语句

1、变量&#xff1a; 在程序运行期间其值可以改变的量称为变量。变量是代码中最重要的元素。每个变量应该有一个名字&#xff0c;同一个程序内的变量名不重复。 请注意区分变量名和变量值这两个不同的概念&#xff08;相当于张三的名字和他本人是不同的概念一样&#xff09;。…

入门matlab

常识 如何建一个新文件 创建新文件&#xff0c;点击新建&#xff0c;我们就可以开始写代码了 为什么要在代码开头加入clear 假如我们有2个文件&#xff0c;第一个文件里面给x赋值100&#xff0c;第二个文件为输出x 依次运行&#xff1a; 结果输出100&#xff0c;这是因为它们…

elasticsearch安装与使用(1)-使用docker安装Elasticsearch

ES的优点&#xff1a; 1、分布式准实时2、提供REST风格的API接口&#xff0c;是用户可解借助任何语言使用https对ES执行请求来完成搜索任务&#xff1b;3、提供聚合功能 1、Elasticsearch安装 docker network create elastic docker pull docker.elastic.co/elasticsearch/e…

MySQL 与 PostgreSQL 关键对比二(SQL语法)

目录 1 详细示例 1.1自动增量列 1.2 字符串连接 1.3 JSON 支持 2 总结 MySQL 和 PostgreSQL 是两种流行的开源关系数据库管理系统&#xff08;RDBMS&#xff09;。尽管它们在许多方面相似&#xff0c;但在 SQL 语法和功能上存在一些显著差异。 以下SQL语句的执行如果需要开…

Redis系列-5 Redis分布式锁

背景&#xff1a; 本文介绍Redis分布式锁的内容&#xff0c;包括Redis相关命令和Lua脚本的介绍&#xff0c;以及操作分布式锁的流程与消息&#xff0c;最后结合Redission源码介绍分布式锁的实现原理。 1.基本命令 1.1 基本键值对的设置 设值: set key value 取值: get key …

深度网络及经典网络简介

深度网络及经典网络简介 导语加深网络一个更深的CNN提高识别精度Data Augmentation 层的加深 经典网络VGGGoogLeNetResNet 高速学习迁移学习GPU分布式学习计算位缩减 强化学习总结参考文献 导语 深度学习简单来说&#xff0c;就是加深了层数的神经网络&#xff0c;前面已经提到…

独立游戏《星尘异变》UE5 C++程序开发日志4——实现任务系统

目录 一、任务的数据结构 二、任务栏 三、随机事件奖励 1.随机事件的结构 2.随机事件池的初始化 3.生成随机事件 本游戏作为工厂游戏&#xff0c;任务系统的主要功能就是给玩家生产的目标和动力&#xff0c;也就是给玩家发布一个需要一定数量某星尘的订单&#xff0c;玩家…

5 种技术,可用于系统中的大数据模型

文章目录 一、说明二、第一种&#xff1a;批量大小三、第二种&#xff1a;主动学习四、第三种&#xff1a;增加代币数量五、第四种&#xff1a; 稀疏激活六、第五种&#xff1a;过滤器和更简单的模型后记 一、说明 以下是本文重要观点的摘要。阅读它以获取更多详细信息/获取原…

【CTF MISC】XCTF GFSJ0170 János-the-Ripper Writeup(文件提取+ZIP压缩包+暴力破解)

Jnos-the-Ripper 暂无 解法 用 winhex 打开&#xff0c;提到了 flag.txt。 用 binwalk 扫描&#xff0c;找到一些 zip 压缩包。 binwalk misc100用 foremost 提取文件。 foremost misc100 -o 100flag.txt 在压缩包里。 但是压缩包需要解压密码。 用 Ziperello 暴力破解。 不…

JAVA-LeetCode 热题 100 第56.合并区间

思路&#xff1a; class Solution {public int[][] merge(int[][] intervals) {if(intervals.length < 1) return intervals;List<int[]> res new ArrayList<>();Arrays.sort(intervals, (o1,o2) -> o1[0] - o2[0]);for(int[] interval : intervals){if(res…

vue2中的插槽使用以及Vuex的使用

插槽分为默认插槽&#xff0c;定名插槽还有作用域插槽 一.默认插槽&#xff0c;定名插槽 //app.vue <template> <div class"container"><CategoryTest title"美食" :listData"foods"><img slot"center" src&qu…

前端 移动端 手机调试 (超简单,超有效 !)

背景&#xff1a;webpack工具构建下的vue项目 1. 找出电脑的ipv4地址 2. 替换 host 3. 手机连接电脑热点或者同一个wifi 。浏览器打开链接即可。