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

互斥量函数组

头文件

#include <pthread.h>

pthread_mutex_init

函数原型

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);

函数参数

        mutex:指向要初始化的互斥量的指针。

        attr:指向互斥量属性对象的指针,若为 NULL 则使用默认属性。

函数返回值

        成功时返回 0,出错时返回错误码。

pthread_mutex_lock

函数原型

int pthread_mutex_lock(pthread_mutex_t *mutex);  

 函数参数

        mutex:指向要锁定的互斥量的指针。

函数返回值

        成功时返回 0,出错时返回错误码。

pthread_mutex_unlock

函数原型

int pthread_mutex_unlock(pthread_mutex_t *mutex);

函数参数

        mutex:指向要解锁的互斥量的指针。

函数返回值

        成功时返回 0,出错时返回错误码。

pthread_mutex_destroy

函数原型

int pthread_mutex_destroy(pthread_mutex_t *mutex);

函数参数

        mutex:指向要销毁的互斥量的指针。

函数返回值

        成功时返回 0,出错时返回错误码。

示例

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <semaphore.h>using namespace std;// 线程的安全问题:多线程访问共享数据,且对共享数据的操作为非原子性操作(不可能被中断的操作)int tickets = 10; // 总票数pthread_mutex_t lock; // 互斥量对象(锁)void* thread_handle2(void* data) 
{char* name = (char*)data;while (true) {pthread_mutex_lock(&lock);if (tickets > 0) {usleep(1);printf("%s已出票,剩余票数是:%d\n", name, --tickets);}else {printf("%s票已售罄\n", name);break;}pthread_mutex_unlock(&lock);}
}int main() 
{pthread_t thread_id;int res = pthread_mutex_init(&lock, NULL); // 互斥量初始化char* s1 = "thread01";char* s2 = "thread02";char* s3 = "thread03";pthread_create(&thread_id, NULL, thread_handle2, s1);pthread_create(&thread_id, NULL, thread_handle2, s2);pthread_create(&thread_id, NULL, thread_handle2, s3);while (true) {}pthread_mutex_destroy(&lock);return 0;
}

结果

相关文章:

  • 谢飞机的Java面试之旅:从Spring Boot到Kubernetes的挑战
  • rockermq多线程消费者配置
  • 【数据可视化-38】基于Plotly得泰坦尼克号数据集的多维度可视化分析
  • 目标跟踪最新文章阅读列表
  • PlatformIO 入门学习笔记(二):开发环境介绍
  • 国标GB28181视频平台EasyGBS打造生产监控智能体系,推动企业数字化升级
  • 2025蓝桥杯省赛网络安全组wp
  • 【Nova UI】十二、打造组件库之按钮组件(上):迈向功能构建的关键一步
  • 准确--如何在自己windows电脑上安装多个nodejs版本,自由切换
  • ES练习册
  • C++ AVL树的实现
  • 《AI大模型应知应会100篇》第38篇:大模型与知识图谱结合的应用模式
  • 【创新实训项目博客】数据库搭建
  • 简单了解Java的I/O流机制与文件读写操作
  • Flink 时态维度表 Join 与缓存机制实战
  • NFC 碰一碰发视频贴牌技术,音频功能的开发实践与技术解析
  • WinForm真入门(17)——NumericUpDown控件详解
  • 全星APQP软件系统:驱动芯片半导体行业研发管理迈向高效与合规新高度
  • 每日算法-250427
  • 【Pandas】pandas DataFrame rtruediv
  • 上海浦东单价超10万楼盘228套房源开盘当天售罄,4月已有三个新盘“日光”
  • 四川邻水县县长石国平拟任县(市、区)党委书记
  • 格力电器去年净利增长一成:消费电器营收下滑4%,一季度净利增长26%
  • 以军称若停火谈判无进展,将大幅扩大加沙军事行动
  • 阿曼外交大臣:伊美下一轮谈判暂定5月3日举行
  • 全球首台环形CT直线加速器在沪正式开机,系我国自主研发