当前位置: 首页 > 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产业链…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了&#xff1a;一行…...

PPT|230页| 制造集团企业供应链端到端的数字化解决方案:从需求到结算的全链路业务闭环构建

制造业采购供应链管理是企业运营的核心环节&#xff0c;供应链协同管理在供应链上下游企业之间建立紧密的合作关系&#xff0c;通过信息共享、资源整合、业务协同等方式&#xff0c;实现供应链的全面管理和优化&#xff0c;提高供应链的效率和透明度&#xff0c;降低供应链的成…...

基础测试工具使用经验

背景 vtune&#xff0c;perf, nsight system等基础测试工具&#xff0c;都是用过的&#xff0c;但是没有记录&#xff0c;都逐渐忘了。所以写这篇博客总结记录一下&#xff0c;只要以后发现新的用法&#xff0c;就记得来编辑补充一下 perf 比较基础的用法&#xff1a; 先改这…...

MODBUS TCP转CANopen 技术赋能高效协同作业

在现代工业自动化领域&#xff0c;MODBUS TCP和CANopen两种通讯协议因其稳定性和高效性被广泛应用于各种设备和系统中。而随着科技的不断进步&#xff0c;这两种通讯协议也正在被逐步融合&#xff0c;形成了一种新型的通讯方式——开疆智能MODBUS TCP转CANopen网关KJ-TCPC-CANP…...

Qt Http Server模块功能及架构

Qt Http Server 是 Qt 6.0 中引入的一个新模块&#xff0c;它提供了一个轻量级的 HTTP 服务器实现&#xff0c;主要用于构建基于 HTTP 的应用程序和服务。 功能介绍&#xff1a; 主要功能 HTTP服务器功能&#xff1a; 支持 HTTP/1.1 协议 简单的请求/响应处理模型 支持 GET…...

基于Docker Compose部署Java微服务项目

一. 创建根项目 根项目&#xff08;父项目&#xff09;主要用于依赖管理 一些需要注意的点&#xff1a; 打包方式需要为 pom<modules>里需要注册子模块不要引入maven的打包插件&#xff0c;否则打包时会出问题 <?xml version"1.0" encoding"UTF-8…...

[Java恶补day16] 238.除自身以外数组的乘积

给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#xff0c;且在 O(n) 时间复杂度…...

Web 架构之 CDN 加速原理与落地实践

文章目录 一、思维导图二、正文内容&#xff08;一&#xff09;CDN 基础概念1. 定义2. 组成部分 &#xff08;二&#xff09;CDN 加速原理1. 请求路由2. 内容缓存3. 内容更新 &#xff08;三&#xff09;CDN 落地实践1. 选择 CDN 服务商2. 配置 CDN3. 集成到 Web 架构 &#xf…...

Java编程之桥接模式

定义 桥接模式&#xff08;Bridge Pattern&#xff09;属于结构型设计模式&#xff0c;它的核心意图是将抽象部分与实现部分分离&#xff0c;使它们可以独立地变化。这种模式通过组合关系来替代继承关系&#xff0c;从而降低了抽象和实现这两个可变维度之间的耦合度。 用例子…...

【C++进阶篇】智能指针

C内存管理终极指南&#xff1a;智能指针从入门到源码剖析 一. 智能指针1.1 auto_ptr1.2 unique_ptr1.3 shared_ptr1.4 make_shared 二. 原理三. shared_ptr循环引用问题三. 线程安全问题四. 内存泄漏4.1 什么是内存泄漏4.2 危害4.3 避免内存泄漏 五. 最后 一. 智能指针 智能指…...