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

基于linux下的高并发服务器开发(第三章)- 3.10 死锁

deadlock.c

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>// 全局变量,所有的线程都共享这一份资源。
int tickets = 1000;// 创建一个互斥量
pthread_mutex_t mutex;void * sellticket(void * arg) {// 卖票while(1) {// 加锁pthread_mutex_lock(&mutex);pthread_mutex_lock(&mutex);if(tickets > 0) {usleep(6000);printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);tickets--;}else {// 解锁pthread_mutex_unlock(&mutex);break;}// 解锁pthread_mutex_unlock(&mutex);pthread_mutex_unlock(&mutex);}return NULL;
}int main() {// 初始化互斥量pthread_mutex_init(&mutex, NULL);// 创建3个子线程pthread_t tid1, tid2, tid3;pthread_create(&tid1, NULL, sellticket, NULL);pthread_create(&tid2, NULL, sellticket, NULL);pthread_create(&tid3, NULL, sellticket, NULL);// 回收子线程的资源,阻塞pthread_join(tid1, NULL);pthread_join(tid2, NULL);pthread_join(tid3, NULL);pthread_exit(NULL); // 退出主线程// 释放互斥量资源pthread_mutex_destroy(&mutex);return 0;
}

deadlock1.c

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>// 创建2个互斥量
pthread_mutex_t mutex1, mutex2;void * workA(void * arg) {pthread_mutex_lock(&mutex1);sleep(1);pthread_mutex_lock(&mutex2);printf("workA....\n");pthread_mutex_unlock(&mutex2);pthread_mutex_unlock(&mutex1);return NULL;
}void * workB(void * arg) {pthread_mutex_lock(&mutex2);sleep(1);pthread_mutex_lock(&mutex1);printf("workB....\n");pthread_mutex_unlock(&mutex1);pthread_mutex_unlock(&mutex2);return NULL;
}int main() {// 初始化互斥量pthread_mutex_init(&mutex1, NULL);pthread_mutex_init(&mutex2, NULL);// 创建2个子线程pthread_t tid1, tid2;pthread_create(&tid1, NULL, workA, NULL);pthread_create(&tid2, NULL, workB, NULL);// 回收子线程资源pthread_join(tid1, NULL);pthread_join(tid2, NULL);// 释放互斥量资源pthread_mutex_destroy(&mutex1);pthread_mutex_destroy(&mutex2);return 0;
}

http://www.lryc.cn/news/95825.html

相关文章:

  • 09.计算机网络——套接字编程
  • Data Structure, Algorithm,and Applications in C++
  • Apipost使用教程
  • 如何使用Python进行服务器管理和自动化操作?
  • Kafka-partition和消费者的关系
  • 使用克拉默法则进行三点定圆(二维)
  • 【Java】Java多线程编程基础
  • FFmpeg-4.2.4的去logo源码分析
  • 深度学习(一)
  • Stream API将对象中的某一字段取出转换为list或数组
  • 什么是Java中的JVM(Java虚拟机)?
  • springboot + redis + 注解 + 拦截器 实现接口幂等性校验
  • PLC编程:关键在于模拟操作流程和实现控制
  • List的各种排序
  • 在自定义数据集上微调Alpaca和LLaMA
  • Python 实现接口类的两种方式+邮件提醒+动态导入模块+反射(参考Django中间件源码)
  • Solr原理剖析
  • 解决 “无法将 ‘npm‘ 项识别为 cmdlet、函数、脚本文件或可运行程序的名称“ 错误的方法
  • Python 电商API 开发最佳实践
  • JAVA基础-集合(List与Map)
  • 19 QListWidget控件
  • 手动安装docsify
  • yaml语法详解
  • ubuntu下tmux安装
  • ssh打开远程vscode
  • Socket发送数据---winsock库和boost库
  • Qt Core学习日记——第七天QMetaObject(上)
  • 100、用简洁的语言描述一下:TCP的三次握手和四次挥手(不需要长篇大论)
  • 中南大学硕士论文latex版本全指导
  • RFC8470在HTTP中使用早期数据