当前位置: 首页 > news >正文

【Linux多线程编程】互斥锁及其使用

1、互斥锁

用于解决竞争问题的一种机制。

什么是竞争,竞争就是多个实体同时获取一个资源,例如多个线程写一个全局变量。

2、Linux如何使用互斥锁

以pthread为例,锁的创建和使用如下:

/* 创建锁 */
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;/* 加锁*/
pthread_mutex_lock(&lock);/* 解锁 */
pthread_mutex_unlock(&lock);

3、多写者问题


#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <pthread.h>/* global variable */
int gValue = 0;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;void *threadFuncReader(void *arg)
{while(1){gValue = 1;if(1 != gValue){printf("\nerror");}// printf("\nthis is [1], read value is [%d]", gValue);usleep(1);}}void *threadFuncWriter(void *arg)
{while(1){gValue = 2;if(2 !=gValue ){printf("\nerror");}else{// printf("\nthis is [2], read value is [%d]", gValue);          }usleep(1);}}void *threadFuncWriter1(void *arg)
{while(1){gValue = 3;if(3 != gValue ){printf("\nerror");}else{//printf("\nthis is [3], read value is [%d]", gValue);          }usleep(1);}}void *threadFuncWriter2(void *arg)
{while(1){gValue = 4;if(4 != gValue ){printf("\nerror");}else{printf("\nthis is [4], read value is [%d]", gValue);          }sleep(1);}}int main(int argc, int **argv)
{/* shared resources */pthread_t tid_reader;pthread_t tid_writer;pthread_t tid_writer1;pthread_t tid_writer2;pthread_create(&tid_reader, NULL, threadFuncReader, NULL);pthread_create(&tid_writer, NULL, threadFuncWriter, NULL);pthread_create(&tid_writer1, NULL, threadFuncWriter1, NULL);pthread_create(&tid_writer2, NULL, threadFuncWriter2, NULL);pthread_join(tid_reader, NULL);pthread_join(tid_writer, NULL);pthread_join(tid_writer1, NULL);pthread_join(tid_writer2, NULL);printf("\n hello world in Linux.");return 0;
}

上述代码由于没有锁,运行结果如下:

this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
error
this is [4], read value is [4]

加锁后的代码:


#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <pthread.h>/* global variable */
int gValue = 0;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;void *threadFuncReader(void *arg)
{while(1){pthread_mutex_lock(&lock);gValue = 1;if(1 != gValue){printf("\nerror");}// printf("\nthis is [1], read value is [%d]", gValue);pthread_mutex_unlock(&lock);usleep(1);}}void *threadFuncWriter(void *arg)
{while(1){pthread_mutex_lock(&lock);gValue = 2;if(2 !=gValue ){printf("\nerror");}else{// printf("\nthis is [2], read value is [%d]", gValue);          }pthread_mutex_unlock(&lock);usleep(1);}}void *threadFuncWriter1(void *arg)
{while(1){pthread_mutex_lock(&lock);gValue = 3;if(3 != gValue ){printf("\nerror");}else{//printf("\nthis is [3], read value is [%d]", gValue);          }pthread_mutex_unlock(&lock);usleep(1);}}void *threadFuncWriter2(void *arg)
{while(1){pthread_mutex_lock(&lock);gValue = 4;if(4 != gValue ){printf("\nerror");}else{printf("\nthis is [4], read value is [%d]", gValue);          }pthread_mutex_unlock(&lock);sleep(1);}}int main(int argc, int **argv)
{/* shared resources */pthread_t tid_reader;pthread_t tid_writer;pthread_t tid_writer1;pthread_t tid_writer2;pthread_create(&tid_reader, NULL, threadFuncReader, NULL);pthread_create(&tid_writer, NULL, threadFuncWriter, NULL);pthread_create(&tid_writer1, NULL, threadFuncWriter1, NULL);pthread_create(&tid_writer2, NULL, threadFuncWriter2, NULL);pthread_join(tid_reader, NULL);pthread_join(tid_writer, NULL);pthread_join(tid_writer1, NULL);pthread_join(tid_writer2, NULL);printf("\n hello world in Linux.");return 0;
}

运行结果:

this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]
this is [4], read value is [4]

相关文章:

【Linux多线程编程】互斥锁及其使用

1、互斥锁 用于解决竞争问题的一种机制。 什么是竞争&#xff0c;竞争就是多个实体同时获取一个资源&#xff0c;例如多个线程写一个全局变量。 2、Linux如何使用互斥锁 以pthread为例&#xff0c;锁的创建和使用如下&#xff1a; /* 创建锁 */ pthread_mutex_t lock PTHR…...

RabbitMQ_00000

MQ的相关概念 RabbitMQ官网地址&#xff1a;https://www.rabbitmq.com RabbitMQ API地址&#xff1a;https://rabbitmq.github.io/rabbitmq-java-client/api/current/ 什么是MQ&#xff1f; MQ(message queue)本质是个队列&#xff0c;FIFO先入先出&#xff0c;只不过队列中…...

【linux】docker下homeassistant和nodered安装及配置

1、homeassistant安装 从 Docker Hub 上拉取 Home Assistant 的镜像文件 docker pull homeassistant/home-assistant 是运行 Home Assistant 容器 docker run -id --name"homeassistant" --privileged --restart always -p 8123:8123 -e TZAisa/Shanghai --nethost…...

Qt扩展-muParser数学公式解析

muParser数学公式解析 一、概述1. 针对速度进行了优化2. 支持的运算符3. 支持的函数4. 用户定义的常量5. 用户定义的变量6. 自定义值识别回调7. 其他功能 二、内置函数三、内置二元运算符四、三元运算符五、内置常量六、源码引入1. 源码文件2. 编译器开关1. MUP_BASETYPE2.MUP_…...

【Matplotlib】figure方法之图形的保存

&#x1f388;个人主页&#xff1a;甜美的江 &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏 &#x1f917;收录专栏&#xff1a;matplotlib &#x1f91d;希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff0c;让我们共同学习、交流进…...

数据库管理-第142期 DBA?DBA!(20240131)

数据库管理142期 2024-01-31 数据库管理-第142期 DBA&#xff1f;DBA&#xff01;&#xff08;20240131&#xff09;正文总结 数据库管理-第142期 DBA&#xff1f;DBA&#xff01;&#xff08;20240131&#xff09; 作者&#xff1a;胖头鱼的鱼缸&#xff08;尹海文&#xff09…...

react 之 zustand

zustand可以说是redux的平替 官网地址&#xff1a;https://zustand-demo.pmnd.rs/ 1.安装 npm i zustand2.基础使用 // zustand import { create } from zustand// 1. 创建store // 语法容易出错 // 1. 函数参数必须返回一个对象 对象内部编写状态数据和方法 // 2. set是用来…...

leetcode-回文链表

234. 回文链表 在此对比的值&#xff0c;不是节点 # Definition for singly-linked list. # class ListNode: # def __init__(self, val0, nextNone): # self.val val # self.next next class Solution:def isPalindrome(self, head: Optional[ListNod…...

Pinia:一个Vue的状态管理库

Pinia的使用方法包括以下步骤&#xff1a; 安装Pinia&#xff1a;通过yarn或npm进行安装&#xff1a; yarn命令&#xff1a; yarn add pinianpm命令&#xff1a; npm install pinia创建根存储&#xff1a;在main.ts中引入Pinia插件&#xff0c;并创建一个根存储。这可以通过创建…...

2024 Flutter 重大更新,Dart 宏(Macros)编程开始支持,JSON 序列化有救

说起宏编程可能大家并不陌生&#xff0c;但是这对于 Flutter 和 Dart 开发者来说它一直是一个「遗憾」&#xff0c;这个「遗憾」体现在编辑过程的代码修改支持上&#xff0c;其中最典型的莫过于 Dart 的 JSON 序列化。 举个例子&#xff0c;目前 Dart 语言的 JSON 序列化高度依…...

云计算概述(云计算类型、技术驱动力、关键技术、特征、特点、通用点、架构层次)(二)

云计算概述&#xff08;二&#xff09; &#xff08;云计算类型、技术驱动力、关键技术、特征、特点、通用点、架构层次&#xff09; 目录 零、00时光宝盒 一、云计算类型&#xff08;以服务的内容或形态来分) 二、云计算的12种技术驱动力 三、云计算的关键技术 四、云计…...

物流平台架构设计与实践

随着电商行业的迅猛发展&#xff0c;物流行业也得到了极大的发展。从最初的传统物流到现在的智慧物流&#xff0c;物流技术和模式也在不断的更新与升级。物流平台作为连接电商和物流的重要媒介&#xff0c;其架构设计和实践显得尤为重要。 一、物流平台架构设计 1. 前端架构设…...

RedHat8.4安装邮件服务器

一、配置发件服务器 1.1 根据现场IP&#xff0c;配置主机名 vim /etc/hosts 192.168.8.120 mail.test.com 将主机名更改为邮件服务器域名mail.test.com 1.2 关闭防火墙&#xff0c;禁止开机启动 systemctl stop firewalld systemctl disable firewalld 1.3 关闭selinux v…...

Linux Shell系列--dirname 去除基本文件名

一、目的 上一篇中我们介绍了basename命令的使用&#xff0c;本篇我们介绍dirname命令&#xff0c;dirname 命令与 basename 互补&#xff0c;它负责删除路径中的基本文件名部分&#xff08;包括扩展名&#xff09;&#xff0c;只保留目录部分。 二、介绍 dirname首先去除字符…...

池化技术的总结

文章目录 1.什么是池化技术2.池化技术的应用一、连接池二、线程池三、内存池 3.池化技术的总结 1.什么是池化技术 池化技术指的是提前准备一些资源&#xff0c;在需要时可以重复使用这些预先准备的资源。 在系统开发过程中&#xff0c;我们经常会用到池化技术。通俗的讲&am…...

H5简约星空旋转引导页源码

H5简约星空旋转引导页源码 源码介绍&#xff1a;一款带有星空旋转背景特效的源码&#xff0c;带有四个按钮 下载地址&#xff1a; https://www.changyouzuhao.cn/11655.html...

前端学习之路(4) vue2和vue3的区别

一. 根节点不同 vue2中必须要有根标签vue3中可以没有根标签&#xff0c;会默认将多个根标签包裹在一个fragement虚拟标签中&#xff0c;有利于减少内存。 二. 组合式API和选项式API 在vue2中采用选项式API&#xff0c;将数据和函数集中起来处理&#xff0c;将功能点切割了当…...

网络原理-TCP/IP(5)

TCP协议 延迟应答 它也是基于滑动窗口,提高效率的一种机制,结合滑动窗口以及流量控制,能够以延迟应答ACK的方式,把反馈的窗口,搞大.核心在于允许范围内,让窗口尽可能大. 如果接收数据的主机立刻返回ACK应答,这时候返回的窗口可能比较小. 1.假设接收端缓冲区为1M.一次收到了5…...

Docker 常用命令详细介绍

Docker 是一个开源的应用容器引擎&#xff0c;它允许开发者打包他们的应用以及依赖包到一个可移植的容器中&#xff0c;然后发布到任何流行的 Linux 机器上&#xff0c;也可以实现虚拟化。容器是完全使用沙箱机制&#xff0c;相互之间不会有任何接口。Docker 使用概率最高的命令…...

10G PON演进到50G PON

10G-PON是万兆无源光网络&#xff0c;光纤链路传输速率能够达到10Gbps。根据ZTE的报告称&#xff0c;截至2023年6月&#xff0c;全球10G PON出货量已超过3000万个PON端口&#xff0c;其中中国市场份额约占80%。 10G PON在中国市场的广泛部署&#xff0c;显着推进了10G PON产业链…...

Unity UI 性能优化终极指南 — Image篇

&#x1f3af; Unity UI 性能优化终极指南 — Image篇 &#x1f9e9; Image 是什么&#xff1f; Image 是UGUI中最常用的基本绘制组件支持显示 Sprite&#xff0c;可以用于背景、按钮图标、装饰等是UI性能瓶颈的头号来源之一&#xff0c;直接影响Draw Call和Overdraw &#x1…...

python打卡day43

复习日 作业&#xff1a; kaggle找到一个图像数据集&#xff0c;用cnn网络进行训练并且用grad-cam做可视化 进阶&#xff1a;并拆分成多个文件 找了个街头食物图像分类的数据集Popular Street Foods&#xff08;其实写代码的时候就开始后悔了&#xff09;&#xff0c;原因在于&…...

Linux下使用nmcli连接网络

Linux下使用nmcli连接网络 介绍 在使用ubuntu系统的时候&#xff0c;有时候不方便使用桌面&#xff0c;使用ssh远程连接&#xff0c;可能需要使用nmcli命令来连接网络。本文将介绍如何使用nmcli命令连接网络。nmcli 是 NetworkManager 的命令行工具&#xff0c;用于管理网络连…...

下载并运行自制RAG框架

项目部署 https://github.com/huangjia2019/rag-project01-framework git clone https://github.com/huangjia2019/rag-project01-framework.git 一 、 前端分部分部署 在 Ubuntu 系统 上安装 Node.js 和 npm&#xff08;Node Package Manager&#xff09;&#xff0c;并初始…...

python直方图

在Python中&#xff0c;绘制直方图&#xff08;Histogram&#xff09;是一项非常常见的任务&#xff0c;通常用于数据可视化&#xff0c;以展示数据的分布情况。Python中有多种库可以绘制直方图&#xff0c;其中最常用的两个库是Matplotlib和Seaborn。此外&#xff0c;Pandas库…...

竞争加剧,美团的战略升维:反内卷、科技与全球化

5月26日&#xff0c;美团发布2025年第一季度业绩报告&#xff0c;交出了一份兼具韧性与创新性的成绩单。 报告显示&#xff0c;公司一季度总营收866亿元&#xff0c;同比增长18%&#xff1b;核心本地商业收入643亿元&#xff0c;同比增长18%&#xff1b;季度研发投入58亿元&a…...

0-EATSA-GNN:基于图节点分类师生机制的边缘感知和两阶段注意力增强图神经网络(code)

code:https://github.com/afofanah/EATSA-GNN. 文章目录 Abstract1. Introduction1.1.动态图场景1.2.EATSA-GNN框架的背景化2. Background2.1.GNN边缘感知挑战2.2.GNN的可解释性问题2.3.EATSA-GNN可解释性3. Related worksAbstract 图神经网络(GNNs)从根本上改变了我们处理和…...

初识vue3(vue简介,环境配置,setup语法糖)

一&#xff0c;前言 今天学习vue3 二&#xff0c;vue简介及如何创建vue工程 Vue 3 简介 Vue.js&#xff08;读音 /vjuː/&#xff0c;类似 “view”&#xff09;是一款流行的渐进式 JavaScript 框架&#xff0c;用于构建用户界面。Vue 3 是其第三代主要版本&#xff0c;于 …...

ONLYOFFICE文档API:更强的安全功能

在数字化办公时代&#xff0c;文档的安全性与隐私保护已成为企业和个人用户的核心关切。如何确保信息在存储、传输及协作过程中的安全&#xff0c;是开发者与IT管理者亟需解决的问题。ONLYOFFICE作为一款功能强大的开源办公套件&#xff0c;不仅提供了高效的文档编辑与协作体验…...

DeepSeek 赋能自动驾驶仿真测试:解锁高效精准新范式

目录 一、自动驾驶仿真测试概述1.1 自动驾驶发展现状1.2 自动驾驶仿真测试流程 二、DeepSeek 技术剖析2.1 DeepSeek 简介2.2 DeepSeek 核心技术原理 三、DeepSeek 在自动驾驶仿真测试中的应用原理3.1 与自动驾驶仿真测试流程的结合点3.2 如何提升仿真测试效果 四、DeepSeek 在自…...