C语言中的线程同步:Mutex与条件变量

C语言pthread互斥锁(mutex)和可重入锁(递归锁recursive)的演示 1 一旦共享资源被互斥锁锁定,则其余线程想访问共享资源必须等待,直到锁被释放。使用mutex的属性,开启递归锁(可重入锁),解决同一线程可重入问题。2 使用normal属性的互斥锁,一旦发生重入逻辑,则阻塞,成为死锁。需要将属性改为recursive 成为可重入的,递归的。unix-like操作系统 gnu_c或兼容c库。演示未使用可重入锁对资源的重入访问。演示使用互斥锁后 线程的执行顺序。1 命令行传参 1 model=1。2 命令行传参 2 model=2。3 命令行传参 3 model=3。 阅读详情

C语言中的线程同步:Mutex与条件变量

在多线程编程中,线程同步是至关重要的技术,能够确保多个线程在共享资源时不会发生冲突。C语言中的线程同步通常通过互斥锁(mutex)和条件变量(condition variable)来实现。这两种同步机制帮助开发者确保线程间的协调,避免数据竞争,确保程序的正确性和性能。

本文将详细介绍C语言中的线程同步机制,重点讲解mutex(互斥锁)与条件变量的使用,包括它们的原理、应用场景和实现方法,帮助开发者理解如何在C语言中高效地实现线程同步。

目录

  1. 线程同步的基本概念
  2. Mutex(互斥锁)概述
  3. 使用Mutex进行线程同步
  4. 条件变量概述
  5. 使用条件变量进行线程同步
  6. Mutex与条件变量的对比与选择
  7. 线程同步的应用场景
  8. 总结

线程同步的基本概念

在多线程编程中,多个线程通常会共享系统资源,例如内存、文件或数据结构。为了避免多个线程同时访问共享资源时产生数据竞争(Data Race),需要通过同步机制来协调线程之间的执行。线程同步确保多个线程在访问共享资源时遵循某种顺序,避免并发问题。

线程同步的目标

  1. 数据一致性:确保多个线程对共享数据的访问不冲突,避免因并发访问导致的数据丢失或不一致。
  2. 死锁避免:避免多个线程因相互等待对方释放资源而无法继续执行,导致系统死锁。
  3. 性能优化:通过合适的同步机制,减少同步开销,提升多线程程序的性能。

C语言中常用的线程同步机制有:互斥锁(mutex)、条件变量(condition variable)、**读写锁(read-write lock)**等。本文重点介绍互斥锁和条件变量的使用方法。


Mutex(互斥锁)概述

互斥锁(mutex)是一种常见的线程同步机制,用于保护共享资源的访问。互斥锁允许同一时间只有一个线程能够访问共享资源。通过对共享资源加锁,其他线程必须等待锁被释放后才能继续访问该资源。

在C语言中,互斥锁通常通过pthread_mutex_t类型来实现,操作包括初始化锁、加锁、解锁等。使用互斥锁可以有效防止多个线程同时访问临界区(critical section)导致的数据不一致。

Mutex的基本操作

  1. 初始化互斥锁:使用pthread_mutex_init()函数初始化一个互斥锁。
  2. 加锁:通过pthread_mutex_lock()函数锁定互斥锁。
  3. 解锁:通过pthread_mutex_unlock()函数解锁互斥锁。
  4. 销毁互斥锁:使用pthread_mutex_destroy()销毁互斥锁。

使用Mutex进行线程同步

下面通过一个简单的例子演示如何使用互斥锁来进行线程同步,防止多个线程同时访问共享资源。

示例:使用Mutex保护共享变量

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
int shared_variable = 0;

void* increment(void* arg) {
   
   
    pthread_mutex_lock(&mutex);  // 加锁,进入临界区
    shared_variable++;
    printf("Thread %ld incremented shared_variable: %d\n", (long)arg, shared_variable);
    pthread_mutex_unlock(&mutex)
C++11线程库 (六) 条件变量 Condition variables 条件变量是一个线程同步术语,它允许多个线程相互通信。 他可以让一部分线程等待(可能超时)另一个线程可能发出的继续执行通知,条件变量与总是和互斥锁相关。————cppref对于条件变量的描述 一、为什么需要条件变量? 简单来说,条件变量可以完成一些特定场合互斥锁不能(高效)完成的工作。他是多线程编程中“等待-唤起”逻辑的基础,条件变量利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使“条件成立”。等待端需要互斥锁的原因是防止在进入等待状态(. 阅读详情

相关推荐

树莓派上的C语言多线程通信实现详解

多线程通信通常涉及到共享资源的读写和线程之间的同步。在C语言中,可以使用pthread库来实现多线程编程。关键的同步机制包括互斥锁(Mutex)和条件变量(Condition Variable)。编译完成后,执行可执行文件,将看到生产者和消费者线程之间的交互,生产和消费的过程,以及缓冲区的变化。以下是一个简单的多线程通信示例,其中一个线程负责生产数据,另一个线程负责消费数据。用于保护共享资源,确保在任一时刻只有一个线程可以访问共享资源。用于在线程之间进行信号通知,实现线程的等待和唤醒。

ByteBox的博客 689

C++11互斥量mutex详解,再也不怕多线程的数据竞争!

mutex又称互斥量,C++ 11中与 mutex相关的类(包括锁类型)和函数都声明在头文件中,所以如果你需要使用 std::mutex,就必须包含头文件。std::mutex,独占的互斥量,不能递归使用。std::time_mutex,带超时的独占互斥量,不能递归使用。std::recursive_mutex,递归互斥量,不带超时功能。std::recursive_timed_mutex,带超时的递归互斥量。

Lion_Long的博客 7191

【数据结构】汉诺塔问题(丰富图解)

经典汉诺塔问题,丰富图解,助你理解。

℉f的博客 4105

华为模拟器eNSP练习题 - HCIA综合实验

华为模拟器eNSP练习题 - HCIA综合实验 题目要求 ISP路由器只能配置IP地址,之后不得进行其他任何配置; 整个内部网络基于192.168.1.0/24进行地址规划; R1/R2之间启动OSPF协议,单区域; PC1-PC4自动获取IP地址; PC1不能telnet R1,PC1外的其他内网pc可以; PC1-PC4可以访问PC5,R2的公网接口只拥有一个公有IP12.0.0.1; 外部的client可以通过域名www.ensp.com访问http server; ISP路由telnet 12.0

炸鸡店老板z的博客 9866

利用图层自动识别算法实现CAD到Revit BIM模型的高效转换 - VS2022与AutoCAD2024开发环境配置指南

本文详细介绍了如何配置VS2022与AutoCAD2024开发环境,并利用图层自动识别算法实现CAD图纸到Revit BIM模型的高效自动化转换。通过解析CAD图层的规律性,该算法能智能识别并分类墙、门、窗等构件,提取几何信息并驱动Revit自动创建三维模型,从而将传统繁琐的人工“翻模”工作转化为高效、准确的自动化流程,大幅提升BIM模型创建效率。

Apple的专栏 1124

dify智能体:日志管理与标注功能详解

日志管理与标注功能是优化聊天助手、Agent、文本生成应用、Chatflow 和工作流等工具交互体验的关键。日志管理允许用户查看、修改和标注日志,帮助回顾和优化交互内容。用户可以通过点击👍或👎按钮快速标注满意度,标注后的日志可用于后续优化和分析。标注功能则支持用户对交互内容进行标记和调整,以提升模型输出质量。此外,用户还可以调整界面语言和时区设置,确保在熟悉的环境中操作。这些功能共同作用,显著提升了交互体验和模型性能。

zyx_bx的博客 2710

4.UE数字人工程运行逻辑及程序逻辑

UE数字人工程运行逻辑及程序逻辑

6084

Oracle19c SYSAUX表空间爆满?手把手教你清理SM/ADVISOR和AUDSYS占用(附完整SQL)

本文详细解析了Oracle19c中SYSAUX表空间爆满的常见原因及解决方案,重点针对SM/ADVISOR和AUDSYS组件的空间占用问题提供了完整的SQL清理脚本。通过诊断查询、空间清理和预防性维护策略,帮助DBA有效管理SYSAUX表空间,确保数据库稳定运行。

weixin_28338005的博客 235

腾讯滑块验证码collect参数逆向与JSVMP对抗实战

本文深入解析腾讯滑块验证码collect参数的逆向过程与JSVMP虚拟机对抗技术。通过详细的环境搭建、抓包分析和JSVMP逆向技巧,揭示collect参数的生成逻辑与加密流程,并提供完整的模拟实现方案和常见问题排查方法,助力开发者突破腾讯天御验证码的防护机制。

weixin_29009501的博客 1573

【车载以太网】ATU(Address Translation Unit / Address Table Unit)

【车载以太网】ATU(Address Translation Unit / Address Table Unit)

天赐好车的博客 150

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

上一篇: C语言中的信号与信号处理
下一篇: C语言的性能优化:内存使用与计算速度
set_one
博客等级 码龄2年 332粉丝 43原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值