72-Linux_线程同步

线程同步

  • 一.什么是线程同步
  • 二.线程同步的方法
    • 1.互斥锁
      • (1)什么是互斥锁
      • (2)互斥锁的接口
      • (3)互斥锁的使用(例题)
    • 2.信号量
      • (1)什么是信号量
      • (2)信号量的接口
      • (3)信号量的使用(例题)
        • a.循环打印ABC
        • b.:主线程获取用户输入,函数线程将用户输入的数据存储到文件中;
    • 3.读写锁
      • (1)读写锁的接口
      • (2)读写锁的使用
    • 4.条件变量
      • (1)什么是条件变量
      • (2)条件变量的接口
      • (3)条件变量的使用(例题)

一.什么是线程同步

一个进程中的所有线程共享同一个地址空间和诸如打开的文件之类的其他资源.一个线程对资源的任何修改都会影响同一个进程中其他线程的环境.因此,需要同步各种线程的活动,以便它们互不干涉且不破坏数据结构.例如,如果两个线程都试图同时往一个双向链表中增加一个元素,则可能会丢失一个元素或者破坏链表结构
线程同步指的是当一个线程在对某个临界资源进行操作时,其他线程都不可以对这个资源进行操作,直到线程完成操作, 其他线程才能操作,也就是协同步调,让线程按预定的先后次序进行运行。 线程同步的方法有四种:互斥锁、信号量、条件变量、读写锁。

二.线程同步的方法

1.互斥锁

(1)什么是互斥锁

在这里插入图片描述

(2)互斥锁的接口

int pthread_mutex_init(pthread_mutex_t *mutex,pthread_mutexattr_t *attr);//attr:锁的属性,不需要传空即可
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
//注意,互斥锁mutex都需要传地址,因为要改变它;

(3)互斥锁的使用(例题)

示例代码如下,函数线程1和函数线程2模拟访问打印机,函数线程1输出第一个字符‘ A’表示开始使用打印机,输出第二个字符‘ A’表示结束使用,函数线程2操作与函数线程1相同。(由于打印机同一时刻只能被一个线程使用,所以输出结果不应该出现 abab)
代码:

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<pthread.h>
#include<stdlib.h>

pthread_mutex_t mutex;

void* fun1(void *arg)
{
    for(int i=0;i<5;i++)
    {
        pthread_mutex_lock(&mutex);//可能阻塞
        printf("A");
        fflush(stdout);
        int n=rand()%3;
        sleep(n);
        printf("A");
        fflush(stdout);
        pthread_mutex_unlock(&mutex);//解锁
        n=rand()%3;
        sleep(n);
    }
}


void* fun2(void *arg)
{
    for(int i=0;i<5;i++)
    {
        pthread_mutex_lock(&mutex);//加锁
        printf("B");
        fflush(stdout);
        int n=rand()%3;
        sleep(n);
        printf("B");
        fflush(stdout);
        pthread_mutex_unlock(&mutex);//解锁
        n=rand()%3;
        sleep(n);
    }
}

int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_t id1,id2;
    pthread_create(&id1,NULL,fun1,NULL);
    pthread_create(&id2,NULL,fun2,NULL);

    pthread_join(id1,NULL);
    pthread_join(id2,NULL);
    pthread_mutex_destroy(&mutex);
    exit(0);
}

运行结果截图:
在这里插入图片描述

2.信号量

(1)什么是信号量

信号量

(2)信号量的接口

int sem_init(sem_t *sem, int pshared, unsigned int value);//信号量的初始化
//sem_init()在sem指向的地址初始化未命名的信号量。这个value参数指定信号量的
初始值(第三个参数)。
//pshared:设置信号量是否在进程间共享,Linux不支持,一般给0; (非0为共享)
int sem_wait(sem_t *sem);//P操作,wait表示等待,相当于是等待获取资源,那么就是P操作
int sem_post(sem_t *sem);//V操作
int sem_destroy(sem_t *sem);/销毁信号量

(3)信号量的使用(例题)

a.循环打印ABC

在这里插入图片描述
代码:

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


sem_t sema;
sem_t semb;
sem_t semc;

void *funa(void *arg)
{
    for(int i=0;i<5;i++)
    {
        sem_wait(&sema);//ps1
        printf("A");
        fflush(stdout);
        sem_post(&semb);//vs2
    }
}
void *funb(void *arg)
{
    for(int i=0;i<5;i++)
    {
        sem_wait(&semb);//ps2
        printf("B");
        fflush(stdout);
        sem_post(&semc);//vs3
    }
}

void *func(void *arg)
{
    for(int i=0;i<5;i++)
    {
        sem_wait(&semc);//ps3
        printf("C");
        fflush(stdout);
        sem_post(&sema);//vs1
    }
}
int main()
{
    sem_init(&sema,0,1);
    sem_init(&semb,0,0);
    sem_init(&semc,0,0);

    pthread_t id1,id2,id3;
    pthread_create(&id1,NULL,funa,NULL);
    pthread_create(&id2,NULL,funb,NULL);
    pthread_create(&id3,NULL,func,NULL);

    pthread_join(id1,NULL);
    pthread_join(id2,NULL);
    pthread_join(id3,NULL);

    sem_destroy(&sema);
    sem_destroy(&semb);
    sem_destroy(&semc);

    exit(0);
}

运行结果截图:
在这里插入图片描述

b.:主线程获取用户输入,函数线程将用户输入的数据存储到文件中;

代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<fcntl.h>
#include<string.h>

sem_t sem1;
sem_t sem2;

char buff[128]={0};

void  funa()
{
    while(1)
    {
        sem_wait(&sem1);
        printf("please input data:");
        fflush(stdout);

        fgets(buff,128,stdin);
        buff[strlen(buff)-1]=0;

        sem_post(&sem2);

        if(strncmp(buff,"end",3)==0)
        {
            break;
        }
    }
}


void *funb(void*arg)
{
    int fd=open("a.txt",O_RDWR|O_CREAT,0664);
    assert(fd!=-1);

    while(1)
    {
        sem_wait(&sem2);
        if(strncmp(buff,"end",3)==0)
        {
            break;
        }
        write(fd,buff,strlen(buff));
        memset(buff,0,128);
        sem_post(&sem1);
    }
    sem_destroy(&sem1);
    sem_destroy(&sem2);
}

int main()
{
    sem_init(&sem1,0,1);
    sem_init(&sem2,0,0);

    pthread_t id;
    int res=pthread_create(&id,NULL,funb,NULL);
    assert(res==0);
    
    funa();

    pthread_exit(NULL);
}

运行结果截图:
在这里插入图片描述
a.txt
在这里插入图片描述

3.读写锁

(1)读写锁的接口

#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t*rwlock,pthread_rwlockattr_t *attr);
//第一个参数是锁的地址,第二个参数是锁的属性
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);//加读锁
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);//加写锁
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);//解锁,不管加的是读锁还是写锁,都用unlock解锁
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);//销毁

(2)读写锁的使用

代码

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<pthread.h>
#include<stdlib.h>

pthread_rwlock_t lock;

void* fun1(void *arg)
{
    for(int i=0;i<10;i++)
    {
        pthread_rwlock_rdlock(&lock);
        printf("fun1 read start---\n");
        sleep(1);
        printf("fun1 read end---\n");
        pthread_rwlock_unlock(&lock);
        sleep(1);
    }
}

void* fun2(void *arg)
{
    for(int i=0;i<5;i++)
    {
        pthread_rwlock_rdlock(&lock);
        printf("fun2 read start---\n");
        sleep(2);
        printf("fun2 read end---\n");
        pthread_rwlock_unlock(&lock);
    }
}
void* fun3(void *arg)
{
    for(int i=0;i<3;i++)
    {
        pthread_rwlock_wrlock(&lock);
        printf("fun3 write start***********\n");
        sleep(3);
        printf("fun3 write end************\n");
        pthread_rwlock_unlock(&lock);

    }
}
int main()
{
    pthread_rwlock_init(&lock,NULL);
    pthread_t id1,id2,id3;
    pthread_create(&id1,NULL,fun1,NULL);
    pthread_create(&id2,NULL,fun2,NULL);
    pthread_create(&id3,NULL,fun3,NULL);

    pthread_join(id1,NULL);
    pthread_join(id2,NULL);
    pthread_join(id3,NULL);

    pthread_rwlock_destroy(&lock);
    exit(0);
}

运行结果截图:
在这里插入图片描述

4.条件变量

(1)什么是条件变量

如果说互斥锁是用于同步线程对共享数据的访问的话,那么条件变量则是用于在线程之间的同步共享数据的值.条件变量提供了一种线程间的通知机制:当某个共享数据达到某个值的时候,唤醒等待这个共享数据的线程.

(2)条件变量的接口

#include <pthread.h>
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *attr);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
//将条件变量添加到等待队列中,阻塞,等待被唤醒;第一个参数是条件变量的地址,第二个参数是互斥锁;
//也就是说条件变量往往伴随着互斥锁的使用;
int pthread_cond_signal(pthread_cond_t *cond); //唤醒单个线程
int pthread_cond_broadcast(pthread_cond_t *cond); //唤醒所有等待的线程
int pthread_cond_destroy(pthread_cond_t *cond);//销毁条件变量

(3)条件变量的使用(例题)

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

pthread_mutex_t mutex;
pthread_cond_t cond;

void *funa(void*arg)
{
    char *s=(char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        pthread_mutex_unlock(&mutex);
        

        if(strncmp(s,"end",3)==0)
        {
            break;
        }
        printf("funa:%s",s);
    }
        

}
void*funb(void*arg)
{
    char *s=(char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        pthread_mutex_unlock(&mutex);

        if(strncmp(s,"end",3)==0)
        {
            break;
        }
        printf("funb:%s",s);
    }
}

int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);

    char buff[128]={0};
    pthread_t id1,id2;
    pthread_create(&id1,NULL,funa,(void*)buff);
    pthread_create(&id2,NULL,funb,(void*)buff);


    while(1)
    {
        fgets(buff,128,stdin);
        if(strncmp(buff,"end",3)==0)
        {
            //唤醒所有线程
            pthread_cond_broadcast(&cond);
            break;
        }
        else
        {
            //唤醒一个线程
            pthread_cond_signal(&cond);
        }
    }
    pthread_join(id1,NULL);
    pthread_join(id2,NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    exit(0);
}

在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

R语言|plot和par函数绘图详解,绘图区域设置 颜色设置 绘图后修改及图像输出

plot()函数 plot()函数是R中最基本的绘图函数&#xff0c;其实最简单、最基础的函数&#xff0c;这也就意味着其具有更多的可操作性。 plot(x,y,...) 在plot函数中&#xff0c;只需指定最基本的x和y轴对应数据即可进行图像的绘制&#xff0c;x和y轴数据分别为两个向量或者是只…

年薪40W测试工程师成长之路,你在哪个阶段?

对任何职业而言&#xff0c;薪资始终都会是众多追求的重要部分。前几年的软件测试行业还是一个风口&#xff0c;随着不断地转行人员以及毕业的大学生疯狂地涌入软件测试行业&#xff0c;目前软件测试行业“缺口”已经基本饱和。当然&#xff0c;我说的是最基础的功能测试的岗位…

WIN10無法再使用 IE 瀏覽器打开网页解决办法

修改 Registry&#xff08;只適用 Win10&#xff09; 微軟已於 2023 年 2 月 14 日永久停用 Internet Explorer&#xff0c;會透過 Edge 的更新讓使用者開啟 IE 時自動導向 Edge&#xff0c;其餘如工作列上的圖示&#xff0c;使用的方法則是透過「品質更新」的 B 更新來達成&am…

NoSQL与Redis五次作业回顾

文章目录1. 作业12. 作业23. 作业34. 作业45. 作业51. 作业1 要求&#xff1a; 在 VM 上安装 CentOS Linux 系统&#xff0c;并在 Linux 上通过 yum 安装 C编译器&#xff0c;对 Redis 进行编译安装。 观察 Redis 目录结构&#xff0c;使用 redis-server 启动服务器&#xff…

Android---Jetpack之DataBinding

DataBinding 的意义 让布局文件承担了部分原本属于页面的工作&#xff0c;使页面与布局耦合度进一步降低。 DataBinding 的应用 使用 dataBinding 需要在 gradle 里添加如下代码 dataBinding{enabled true} 应用实现 activity_main.xml <?xml version"1.0" e…

python argparse的使用,本文基本够用

一、前言 在学习深度学习会发现都比较爱用python这个argparse&#xff0c;虽然基本能理解&#xff0c;但没有仔细自己动手去写&#xff0c;因此这里写下来作为自己本人的学习笔记 argparse是python的一个命令行参数解析包&#xff0c;在代码需要频繁修改参数时&#xff0c;方便…

Shell编程之免交互

目录交互的概念与Linux中的运用Here Document 免交互tee命令重定向输出加标准输出支持变量替换多行注释Expect实例操作免交互预设值修改用户密码创建用户并设置密码实现 ssh 自动登录交互的概念与Linux中的运用 交互&#xff1a;当计算机播放某多媒体程序的时候&#xff0c;编…

步进频雷达的一维距离像matlab仿真

步进频雷达的一维距离像matlab仿真发射与回波信号模型距离高分辨原理仿真分析不进行步进频高分辨一维距离像进行步进频高分辨一维距离像代码发射与回波信号模型 步进频率信号发射得的是一串窄带的相参脉冲&#xff0c;每个脉冲的载频之间是均匀线性步进的&#xff0c;经过相参本…

Spring依赖注入详解

1.set注入 启动容器后看看到底能不能拿到teacherService的值。可以看到拿到了值。我们具体来分析怎么注入的 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 发现pvs里面有一个我们自己set的值 直接进行属性赋值。 org.springf…

【创作赢红包】Python第3章 流程控制

这里写目录标题【本章导读】真值测试比较运算成员运算for循环while循环项目实训1项目实训2项目实训3项目实训4&#xff1a;项目实训5&#xff1a;项目实训6&#xff1a;项目实训7&#xff1a;项目实训8项目实训9&#xff1a;项目实训10:项目实训11&#xff1a;项目实训12&#…

【Redis7】Redis7 十大数据类型

【大家好&#xff0c;我是爱干饭的猿&#xff0c;本文重点介绍Redis7 十大数据类型。 后续会继续分享Redis7和其他重要知识点总结&#xff0c;如果喜欢这篇文章&#xff0c;点个赞&#x1f44d;&#xff0c;关注一下吧】 上一篇文章&#xff1a;《【Redis7】Redis7概述、安装…

PCB生产工艺流程五:PCB生产工艺流程的第3步,钻孔的分类及目的

PCB生产工艺流程五&#xff1a;PCB生产工艺流程的第3步&#xff0c;钻孔的分类及目的 今天第五期的内容就是详细讲述PCB工艺流程第三步——钻孔&#xff0c;忘记第二步的小伙伴看这里 PCB工艺流程第2步&#xff0c;你了解多少&#xff1f; 钻孔的目的 在板面上钻出层与层之间…

【Java项目】SpringBoot实现一个请求同时上传多个文件和类并附上代码实例

文章目录前言文件多线程兼多文件上传RequestParam和RequestPart的区别前言 项目在做二手市场&#xff0c;然后商品的提交我们希望对商品的描述和商品的照片能一起传递到同一个接口来统一处理&#xff0c;而不是分发到两个接口中去处理&#xff0c;因为如果分到两个接口那么会特…

大语言模型带来的一些启发

仅代表个人看法&#xff0c;不喜勿喷。 The limits of my language means the limits of my world. (Ludwig Wittgenstein) 我的语言的极限意味着我的世界的极限。——维特根斯坦 大语言模型解决的不仅是处理文本相关问题&#xff0c;它带来的是人对世界的理解&#xff0c;或者…

华为网络篇 单臂路由-17

实验难度 2实验复杂度2目录 一、实验原理 二、实验拓扑 三、实验步骤 四、实验过程 总结 一、实验原理 单臂路由&#xff08;router-on-a-stick&#xff09;是指在路由器的一个接口上通过配置子接口&#xff08;或“逻辑接口”&#xff0c;并不存在真正物理接口&…

EasyExcel的简单使用(easyExcel和poi)

EasyExcel的简单使用 前言 Excel读 1.实体类 2.读监听器与测试类 3.输出结果 Excel写 1.实体类 2.写入Excel的测试类 3.输出结果 填充Excel 1.Excel模板 2.测试类 3.输出结果 前言 EasyExcel类是一套基于Java的开源Excel解析工具类&#xff0c;相较于传统的框架如Apache poi、…

Go 语言数组和切片的区别

原文链接&#xff1a; Go 语言数组和切片的区别 在 Go 语言中&#xff0c;数组和切片看起来很像&#xff0c;但其实它们又有很多的不同之处&#xff0c;这篇文章就来说说它们到底有哪些不同。 另外&#xff0c;这个问题在面试中也经常会被问到&#xff0c;属于入门级题目&…

堆及其堆排序

堆是一种特殊的数据结构&#xff0c;底层实现是靠数组存储以及完全二叉树的性质 文章目录一、堆概念二、堆实现三、堆源码四、堆排序一、堆概念 完全二叉树用数组来存储可以达到空间的有效利用且可以直观反映它们之间的逻辑关系&#xff0c;双亲与孩子之间的关系。一般在数组中…

一文说透虚拟内存

为什么我们需要虚拟内存 提供一个虚拟化封装&#xff0c;让上层的程序员不用担心内存分配&#xff0c;物理地址的总大小。同时如果要手动管理内存是一件麻烦的事&#xff0c;比如一个程序读到另一个程序的物理地址&#xff0c;并且也很难保障多个处理器不会同时读取写入同一块…

GitHub Action 使用

GitHub Action 使用 GitHub Actions 是一种持续集成和持续交付 (CI/CD) 平台&#xff0c;可用于自动执行生成、测试和部署管道。 您可以创建工作流程来构建和测试存储库的每个拉取请求&#xff0c;或将合并的拉取请求部署到生产环境。GitHub 提供 Linux、Windows 和 macOS 虚拟…
最新文章