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

从零实现富文本编辑器#5-编辑器选区模型的状态结构表达

先前我们总结了浏览器选区模型的交互策略&#xff0c;并且实现了基本的选区操作&#xff0c;还调研了自绘选区的实现。那么相对的&#xff0c;我们还需要设计编辑器的选区表达&#xff0c;也可以称为模型选区。编辑器中应用变更时的操作范围&#xff0c;就是以模型选区为基准来…...

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

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

测试markdown--肇兴

day1&#xff1a; 1、去程&#xff1a;7:04 --11:32高铁 高铁右转上售票大厅2楼&#xff0c;穿过候车厅下一楼&#xff0c;上大巴车 &#xffe5;10/人 **2、到达&#xff1a;**12点多到达寨子&#xff0c;买门票&#xff0c;美团/抖音&#xff1a;&#xffe5;78人 3、中饭&a…...

质量体系的重要

质量体系是为确保产品、服务或过程质量满足规定要求&#xff0c;由相互关联的要素构成的有机整体。其核心内容可归纳为以下五个方面&#xff1a; &#x1f3db;️ 一、组织架构与职责 质量体系明确组织内各部门、岗位的职责与权限&#xff0c;形成层级清晰的管理网络&#xf…...

第 86 场周赛:矩阵中的幻方、钥匙和房间、将数组拆分成斐波那契序列、猜猜这个单词

Q1、[中等] 矩阵中的幻方 1、题目描述 3 x 3 的幻方是一个填充有 从 1 到 9 的不同数字的 3 x 3 矩阵&#xff0c;其中每行&#xff0c;每列以及两条对角线上的各数之和都相等。 给定一个由整数组成的row x col 的 grid&#xff0c;其中有多少个 3 3 的 “幻方” 子矩阵&am…...

安全突围:重塑内生安全体系:齐向东在2025年BCS大会的演讲

文章目录 前言第一部分&#xff1a;体系力量是突围之钥第一重困境是体系思想落地不畅。第二重困境是大小体系融合瓶颈。第三重困境是“小体系”运营梗阻。 第二部分&#xff1a;体系矛盾是突围之障一是数据孤岛的障碍。二是投入不足的障碍。三是新旧兼容难的障碍。 第三部分&am…...

【WebSocket】SpringBoot项目中使用WebSocket

1. 导入坐标 如果springboot父工程没有加入websocket的起步依赖&#xff0c;添加它的坐标的时候需要带上版本号。 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId> </dep…...

在 Visual Studio Code 中使用驭码 CodeRider 提升开发效率:以冒泡排序为例

目录 前言1 插件安装与配置1.1 安装驭码 CodeRider1.2 初始配置建议 2 示例代码&#xff1a;冒泡排序3 驭码 CodeRider 功能详解3.1 功能概览3.2 代码解释功能3.3 自动注释生成3.4 逻辑修改功能3.5 单元测试自动生成3.6 代码优化建议 4 驭码的实际应用建议5 常见问题与解决建议…...

[USACO23FEB] Bakery S

题目描述 Bessie 开了一家面包店! 在她的面包店里&#xff0c;Bessie 有一个烤箱&#xff0c;可以在 t C t_C tC​ 的时间内生产一块饼干或在 t M t_M tM​ 单位时间内生产一块松糕。 ( 1 ≤ t C , t M ≤ 10 9 ) (1 \le t_C,t_M \le 10^9) (1≤tC​,tM​≤109)。由于空间…...

轻量级Docker管理工具Docker Switchboard

简介 什么是 Docker Switchboard &#xff1f; Docker Switchboard 是一个轻量级的 Web 应用程序&#xff0c;用于管理 Docker 容器。它提供了一个干净、用户友好的界面来启动、停止和监控主机上运行的容器&#xff0c;使其成为本地开发、家庭实验室或小型服务器设置的理想选择…...