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

互斥量函数组

头文件

#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;
}

结果

http://www.xdnf.cn/news/2484.html

相关文章:

  • List 的介绍 [数据结构 初阶]
  • Missashe考研日记-day28
  • 海关 瑞数 后缀分析 rs
  • 详解React Fiber架构中,reconcile阶段的具体工作流程
  • 使用 Doxygen 生成类似官网的专业文档
  • 【黑马JavaWeb+AI知识梳理】前端Web基础02 - JS+Vue+Ajax
  • WSL2里手动安装Docker 遇坑
  • 234. 回文链表(java)
  • 李沐动手深度学习(pycharm中运行笔记)——07.自动求导
  • Kaamel白皮书:IoT设备安全隐私评估实践
  • Golang | 向倒排索引上添加删除文档
  • 每天五分钟深度学习框架pytorch:使用visdom绘制损失函数图像
  • 布隆过滤器(Bloom Filter)简介
  • Vue Router 核心指南:构建高效单页应用的导航艺术
  • 用Python做有趣的AI项目4:AI 表情识别助手
  • Linux:基础IO 文件系统
  • 吴恩达深度学习作业之风格转移Neural Style Transfer (pytorch)
  • 【创新实训项目博客】数据库搭建
  • pikachu靶场-敏感信息泄露
  • 深圳市富力达:SAP一体化管理助力精密制造升级 | 工博科技SAP客户案例
  • 在Azure Databricks中实现缓慢变化维度(SCD)的三种类型
  • 服务器不能复制粘贴文件的处理方式
  • 信竞中的数学(一):质数
  • 关于 React Fiber 架构、Hooks 原理
  • 机器学习的一百个概念(13)布里尔分数
  • OkHttp源码梳理
  • 数字后端设计 (六):验证——给芯片做「超严格体检」
  • 苍穹外卖(缓存商品、购物车)
  • 基于Qt5的蓝牙打印开发实战:从扫描到小票打印的全流程
  • 关系型数据库PostgreSQL vs MySQL 深度对比:专业术语+白话解析+实战案例