死锁检测组件原理及代码实现

news/2024/5/19 1:33:59/文章来源:https://blog.csdn.net/weixin_46935110/article/details/127036005

一、引言

所谓死锁,是指多个线程或进程各自持有某些资源,同时又等待着别的线程或进程释放它们现在所保持的资源,否则就不能向前推进。如下图:线程各自占有一把锁,还需要申请别的线程当前持有的锁,形成锁资源的循环等待,这就是死锁。
在这里插入图片描述
从上图中,我们可以看到,死锁一定伴随某种循环资源的赖,也就是形成了闭环,所谓死锁检测,就是只要能检测出环的存在,就能检测到死锁。

二、hook技术

Hook技术又叫做钩子函数,原理是在系统没有调用该函数之前,钩子程序就先捕获该消息,并得到控制权。这时我们就可以在钩子函数执行自己的代码片段。底层原理实际上是利用动态加载的过程中替换原有函数符号的地址,来执行我们自定义的钩子函数。

dlsym函数

void* dlsym(void* handle, char* symbol);

dlsym()函数是动态加载的核心函数,其中,第二个参数就是所要查找的符号。如果找到该符号,返回该符号的值;没有找到返回NULL。它的返回值对于不同类型的符号,意义是不同的。如果查找的是函数,返回的就是函数地址;如果是变量,返回的是变量的地址。

以下为钩子函数的示例:

#define _GNU_SOURCE
#include <dlfcn.h>typedef int (*pthread_mutex_lock_t)(pthread_mutex_t *mutex);
pthread_mutex_lock_t pthread_mutex_lock_f;typedef int (*pthread_mutex_unlock_t)(pthread_mutex_t *mutex);
pthread_mutex_unlock_t pthread_mutex_unlock_f;static int init_hook() {// 使用dlsym函数获取系统pthread_mutex_lock和pthread_mutex_unlock的地址pthread_mutex_lock_f = dlsym(RTLD_NEXT, "pthread_mutex_lock");pthread_mutex_unlock_f = dlsym(RTLD_NEXT, "pthread_mutex_unlock");
}int pthread_mutex_lock(pthread_mutex_t *mutex) {// TODO whatever you wantpthread_mutex_lock_f(mutex);  // 执行系统真正的pthread_mutex_lock函数// TODO whatever you want
}int pthread_mutex_unlock(pthread_mutex_t *mutex) {// TODO whatever you wantpthread_mutex_unlock_f(mutex);  // 执行系统真正的pthread_mutex_unlock函数// TODO whatever you want
}

三、死锁检测原理

这种资源的依赖关系,可以使用数据结构有向图来构建,如果对图不了解的同学戳这里。如线程A想要获取线程B已占有的资源,则建立一条A指向B的关系。有向图可以参考数据结构——图详解及代码实现。

四、死锁检测完整代码实现

#define _GNU_SOURCE
#include <dlfcn.h>#include <stdio.h>
#include <pthread.h>
#include <unistd.h>#include <stdlib.h>
#include <stdint.h>#define THREAD_NUM      10typedef unsigned long int uint64;typedef int (*pthread_mutex_lock_t)(pthread_mutex_t *mutex);
pthread_mutex_lock_t pthread_mutex_lock_f;typedef int (*pthread_mutex_unlock_t)(pthread_mutex_t *mutex);
pthread_mutex_unlock_t pthread_mutex_unlock_f;#if 1 // graph#define MAX		100enum Type {PROCESS, RESOURCE};struct source_type {uint64 id;enum Type type;uint64 lock_id;int degress;
};struct vertex {struct source_type s;struct vertex *next;
};struct task_graph {struct vertex list[MAX];int num;struct source_type locklist[MAX];int lockidx;pthread_mutex_t mutex;
};struct task_graph *tg = NULL;
int path[MAX+1];
int visited[MAX];
int k = 0;
int deadlock = 0;struct vertex *create_vertex(struct source_type type) {struct vertex *tex = (struct vertex *)malloc(sizeof(struct vertex ));tex->s = type;tex->next = NULL;return tex;
}int search_vertex(struct source_type type) {int i = 0;for (i = 0;i < tg->num;i ++) {if (tg->list[i].s.type == type.type && tg->list[i].s.id == type.id) {return i;}}return -1;
}void add_vertex(struct source_type type) {if (search_vertex(type) == -1) {tg->list[tg->num].s = type;tg->list[tg->num].next = NULL;tg->num ++;}
}int add_edge(struct source_type from, struct source_type to) {add_vertex(from);add_vertex(to);struct vertex *v = &(tg->list[search_vertex(from)]);while (v->next != NULL) {v = v->next;}v->next = create_vertex(to);
}int verify_edge(struct source_type i, struct source_type j) {if (tg->num == 0) return 0;int idx = search_vertex(i);if (idx == -1) {return 0;}struct vertex *v = &(tg->list[idx]);while (v != NULL) {if (v->s.id == j.id) return 1;v = v->next;}return 0;
}int remove_edge(struct source_type from, struct source_type to) {int idxi = search_vertex(from);int idxj = search_vertex(to);if (idxi != -1 && idxj != -1) {struct vertex *v = &tg->list[idxi];struct vertex *remove;while (v->next != NULL) {if (v->next->s.id == to.id) {remove = v->next;v->next = v->next->next;free(remove);break;}v = v->next;}}
}void print_deadlock(void) {int i = 0;printf("deadlock : ");for (i = 0;i < k-1;i ++) {printf("%ld --> ", tg->list[path[i]].s.id);}printf("%ld\n", tg->list[path[i]].s.id);
}int DFS(int idx) {struct vertex *ver = &tg->list[idx];if (visited[idx] == 1) {path[k++] = idx;print_deadlock();deadlock = 1;return 0;}visited[idx] = 1;path[k++] = idx;while (ver->next != NULL) {DFS(search_vertex(ver->next->s));k --;ver = ver->next;}return 1;
}int search_for_cycle(int idx) {struct vertex *ver = &tg->list[idx];visited[idx] = 1;k = 0;path[k++] = idx;while (ver->next != NULL) {int i = 0;for (i = 0;i < tg->num;i ++) {if (i == idx) continue;visited[i] = 0;}for (i = 1;i <= MAX;i ++) {path[i] = -1;}k = 1;DFS(search_vertex(ver->next->s));ver = ver->next;}
}#if 0  
int main() {tg = (struct task_graph*)malloc(sizeof(struct task_graph));tg->num = 0;struct source_type v1;v1.id = 1;v1.type = PROCESS;add_vertex(v1);struct source_type v2;v2.id = 2;v2.type = PROCESS;add_vertex(v2);struct source_type v3;v3.id = 3;v3.type = PROCESS;add_vertex(v3);struct source_type v4;v4.id = 4;v4.type = PROCESS;add_vertex(v4);struct source_type v5;v5.id = 5;v5.type = PROCESS;add_vertex(v5);add_edge(v1, v2);add_edge(v2, v3);add_edge(v3, v4);add_edge(v4, v5);add_edge(v3, v1);search_for_cycle(search_vertex(v1));}
#endif#endifvoid check_dead_lock(void) {int i = 0;deadlock = 0;for (i = 0;i < tg->num;i ++) {if (deadlock == 1) break;search_for_cycle(i);}if (deadlock == 0) {printf("no deadlock\n");}}static void *thread_routine(void *args) {while (1) {sleep(2);check_dead_lock();}
}void start_check(void) {tg = (struct task_graph*)malloc(sizeof(struct task_graph));tg->num = 0;tg->lockidx = 0;pthread_t tid;pthread_create(&tid, NULL, thread_routine, NULL);
}#if 1int search_lock(uint64 lock) {int i = 0;for (i = 0;i < tg->lockidx;i ++) {if (tg->locklist[i].lock_id == lock) {return i;}}return -1;
}int search_empty_lock(uint64 lock) {int i = 0;for (i = 0;i < tg->lockidx;i ++) {if (tg->locklist[i].lock_id == 0) {return i;}}return tg->lockidx;
}#endifint inc(int *value, int add) {int old;__asm__ volatile("lock;xaddl %2, %1;": "=a"(old): "m"(*value), "a" (add): "cc", "memory");return old;
}void print_locklist(void) {int i = 0;printf("print_locklist: \n");printf("---------------------\n");for (i = 0;i < tg->lockidx;i ++) {printf("threadid : %ld, lockid: %ld\n", tg->locklist[i].id, tg->locklist[i].lock_id);}printf("---------------------\n\n\n");
}void lock_before(uint64 thread_id, uint64 lockaddr) {int idx = 0;// list<threadid, toThreadid>for(idx = 0;idx < tg->lockidx;idx ++) {if ((tg->locklist[idx].lock_id == lockaddr)) {struct source_type from;from.id = thread_id;from.type = PROCESS;add_vertex(from);struct source_type to;to.id = tg->locklist[idx].id;tg->locklist[idx].degress++;to.type = PROCESS;add_vertex(to);if (!verify_edge(from, to)) {add_edge(from, to); // }}}
}void lock_after(uint64 thread_id, uint64 lockaddr) {int idx = 0;if (-1 == (idx = search_lock(lockaddr))) {  // lock list opera int eidx = search_empty_lock(lockaddr);tg->locklist[eidx].id = thread_id;tg->locklist[eidx].lock_id = lockaddr;inc(&tg->lockidx, 1);} else {struct source_type from;from.id = thread_id;from.type = PROCESS;struct source_type to;to.id = tg->locklist[idx].id;tg->locklist[idx].degress --;to.type = PROCESS;if (verify_edge(from, to))remove_edge(from, to);tg->locklist[idx].id = thread_id;}
}void unlock_after(uint64 thread_id, uint64 lockaddr) {int idx = search_lock(lockaddr);if (tg->locklist[idx].degress == 0) {tg->locklist[idx].id = 0;tg->locklist[idx].lock_id = 0;//inc(&tg->lockidx, -1);}
}int pthread_mutex_lock(pthread_mutex_t *mutex) {pthread_t selfid = pthread_self(); //lock_before(selfid, (uint64)mutex);pthread_mutex_lock_f(mutex);lock_after(selfid, (uint64)mutex);}int pthread_mutex_unlock(pthread_mutex_t *mutex) {pthread_t selfid = pthread_self();pthread_mutex_unlock_f(mutex);unlock_after(selfid, (uint64)mutex);
}static int init_hook() {pthread_mutex_lock_f = dlsym(RTLD_NEXT, "pthread_mutex_lock");pthread_mutex_unlock_f = dlsym(RTLD_NEXT, "pthread_mutex_unlock");
}#if 1pthread_mutex_t mutex_1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_3 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_4 = PTHREAD_MUTEX_INITIALIZER;void *thread_rountine_1(void *args)
{pthread_t selfid = pthread_self(); //printf("thread_routine 1 : %ld \n", selfid);pthread_mutex_lock(&mutex_1);sleep(1);pthread_mutex_lock(&mutex_2);pthread_mutex_unlock(&mutex_2);pthread_mutex_unlock(&mutex_1);return (void *)(0);
}void *thread_rountine_2(void *args)
{pthread_t selfid = pthread_self(); //printf("thread_routine 2 : %ld \n", selfid);pthread_mutex_lock(&mutex_2);sleep(1);pthread_mutex_lock(&mutex_3);pthread_mutex_unlock(&mutex_3);pthread_mutex_unlock(&mutex_2);return (void *)(0);
}void *thread_rountine_3(void *args)
{pthread_t selfid = pthread_self(); //printf("thread_routine 3 : %ld \n", selfid);pthread_mutex_lock(&mutex_3);sleep(1);pthread_mutex_lock(&mutex_4);pthread_mutex_unlock(&mutex_4);pthread_mutex_unlock(&mutex_3);return (void *)(0);
}void *thread_rountine_4(void *args)
{pthread_t selfid = pthread_self(); //printf("thread_routine 4 : %ld \n", selfid);pthread_mutex_lock(&mutex_4);sleep(1);pthread_mutex_lock(&mutex_1);pthread_mutex_unlock(&mutex_1);pthread_mutex_unlock(&mutex_4);return (void *)(0);
}int main()
{init_hook();start_check();printf("start_check\n");pthread_t tid1, tid2, tid3, tid4;pthread_create(&tid1, NULL, thread_rountine_1, NULL);pthread_create(&tid2, NULL, thread_rountine_2, NULL);pthread_create(&tid3, NULL, thread_rountine_3, NULL);pthread_create(&tid4, NULL, thread_rountine_4, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);pthread_join(tid3, NULL);pthread_join(tid4, NULL);return 0;
}#endif

运行结果:
在这里插入图片描述可以看到检测到了死锁,线程1->2->3->4->1.

文章参考于<零声教育>的C/C++linux服务期高级架构

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_203625.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Cisco简单配置(十四)—第一跳冗余协议—HSRP

为什么使用第一跳冗余 默认网关限制 如果路由器或路由器接口&#xff08;作为默认网关&#xff09;发生故障&#xff0c;配置该默认网关的主机将与外部网络隔离。在交换网络中&#xff0c;每个客户端仅收到一个默认网关。即使存在第二个路由可以从本地网段传输数据包&#xf…

微信小程序 java高校新生报到宿舍安排管理系统python php

将小程序权限按管理员和用户这两类涉及用户划分。 (a) 管理员&#xff1b;管理员使用本程序涉到的功能主要有&#xff1a;个人中心、宿舍管理、学生管理、宿舍安排管理、缴费信息管理、程序管理等功能 (b)用户进入程序前台可以实现首页、互助沟通、我的等功能 uni-app框架&…

基于java校园志愿者管理系统(java毕业设计)

基于java校园志愿者管理系统 校园志愿者系统是基于java编程语言&#xff0c;mysql数据库&#xff0c;springboot框架&#xff0c;idea开发工具进行开发&#xff0c;本系统主要分为志愿者和管理员两个角色&#xff0c;其中志愿者的主要功能是查看系统公告&#xff0c;活动信息&…

红队工具合集,安全er值得拥有

背景 圈内很多师傅一直在做红队安全工具箱,用于在hvv、渗透等工作中提升工作效率。依照ATT&CK威胁图谱的指导,我们很容易整理出常用的红队工具合集,在这里为大家展示。 工具介绍 信息搜集 信息搜集一直是渗透测试工作开展的重中之重,找到无人关注的老旧应用,先对…

leetcode 617. Merge Two Binary Trees 合并二叉树(简单)

直接用递归调用给定函数,先判断如果root1为空返回root2,如果root2为空返回root1,都存在的情况下建立新节点node,然后对root1和root2的左子节点调用递归并赋给node的左子节点,再对root1和root2的右子节点调用递归并赋给node的右子节点,返回node即可。一、题目大意 给你两棵…

虚拟机安装

ubuntu 虚拟机安装配置&#xff0c;以 18.04 为例 一、安装步骤 > 安装 vmware wmware 下载地址 &#xff1a; download 点击进入下载界面 点击并下载 windows 平台下的安装包 安装时直接一键下一步即可&#xff0c;也可根据自己需求勾选&#xff0c;最后的注册码可以自行…

吃个晚饭的时间,看明白三相交流感应电机驱动原理

&#x1f495;三相交流感应单机驱动方式 物理开关&#xff1a;&#xff08;接触器开关、正反向控制&#xff0c;星三角启动&#xff09; 变频驱动&#xff1a;&#xff08;软启动、变频器调速、一般无星三角启动&#xff09; &#x1f495;一、物理开关驱动 &#x1f91e;该电…

一般勒索要钱,医疗勒索“要命”!重保时期别让患者病无所依

最近&#xff0c;美宾夕法尼亚州医疗机构遭受勒索软件攻击&#xff0c;攻击者访问75628个人的健康信息&#xff0c;包含姓名、地址、电子邮件地址、出生日期、医疗诊断等信息。事实上&#xff0c;近年来全球医疗系统遭遇网络攻击的事件时有发生。2022年8月法国一家医院遭到勒索…

基于JAVA的TCP网络QQ聊天工具系统

目 录 1 功能设计 1 1.1功能概述 1 1.2功能模块图 1 2 逻辑设计 2 3 界面设计 4 3.1注册界面&#xff1a; 4 3.2登录界面 5 3.3好友列表页面 5 3.4好友聊天页面 6 3.5服务器界面 7 4 各模块详细设计 7 4.1登录模块 7 4.2注册模块 9 4.3聊天模块 10 4.4数据库工具类 12 4.5封装的…

springboot+vue外卖点餐系统 计科专业毕业设计选题 java餐厅点餐系统 ssm外卖订餐系统 外卖配送管理系统 java点餐系统

springboot+vue外卖点餐系统 计科专业毕业设计选题 java餐厅点餐系统 ssm外卖订餐系统 外卖配送管理系统 java点餐系统💖💖作者:IT跃迁谷毕设展 💙💙个人简介:曾长期从事计算机专业培训教学,本人也热爱上课教学,语言擅长Java、微信小程序、Python、Golang、安卓And…

基于Logistic回归麻雀算法-附代码

基于Logistic回归麻雀算法 文章目录基于Logistic回归麻雀算法1.麻雀搜索算法2.改进麻雀算法2.1 逐维小孔成像反向学习优化发现者位置2.2 基于 Logistic 模型的自适应因子3.实验结果4.参考文献5.Matlab代码6.python代码摘要&#xff1a;针对麻雀搜索算法后期种群多样性减少、易陷…

ajax 和 react 最显着的区别是什么?

ajax 和 react 最显着的区别是什么?What’s the most remarkable difference between ajax and react? 目前,Ajax 和 React 之间最大的区别之一是它们是帮助不同网页或应用程序以某种方式工作以使用户体验尽可能愉快的进程。 其他 Ajax 和 React 的区别 是一种主要用作开发用…

【JDBC实战】水果库存系统 [功能实现](接口实现类FruitDAOImpl的功能实现)万字长文

CSDN话题挑战赛第2期 参赛话题&#xff1a;学习笔记 JDBC专栏 &#xff08;点击进入专栏&#xff09; 【1】idea添加mysql-jar包 【2】使用IDEA连接数据库&#xff0c;执行增删改操作。 【3】IDEA连接数据库&#xff0c;执行查询操作&#xff0c;返回结果集并输出。 【4】JDBC…

30+行业头部企业相聚杭城,创邻科技“Graph+X”生态合作伙伴大会成功举办

9月22日&#xff0c;2022创邻科技“GraphX”生态合作伙伴大会在浙江杭州圆满落幕&#xff01;北明软件、京东数科、华为云、浙大网新、麒麟软件、同盾科技等30余家行业头部企业50多位企业家、技术领袖、行业精英&#xff0c;齐聚杭城&#xff0c;共享图技术多元场景的前沿资讯&…

免费综合网络研讨会:如何优化 JavaScript 应用程序的方法

免费综合网络研讨会:如何优化 JavaScript 应用程序的方法您是否考虑过提高 JavaScript 应用程序的性能? 加入 Dmytro Mezhenskyi , 开发专家 解码前端 , 上 2022 年 9 月 30 日——美国东部时间上午 11 点, 并了解可用于加速应用程序的各种优化技术。 网络研讨会将涵盖广泛…

【面试系列】Java面试知识篇(八)

个人简介&#xff1a; &#x1f4e6;个人主页&#xff1a;赵四司机 &#x1f3c6;学习方向&#xff1a;JAVA后端开发 &#x1f4e3;种一棵树最好的时间是十年前&#xff0c;其次是现在&#xff01; &#x1f514;博主推荐网站&#xff1a;牛客网 刷题|面试|找工作神器 &#x1…

跨境电商如何利用Quora帮你引上万流量

做跨境电商的&#xff0c;免不了产品推广&#xff0c;想要要获得效果&#xff0c;必须要获得流量。一般流量获取无非分两种&#xff1a;付费和免费流量。●付费流量包括&#xff1a;fb广告,google广告&#xff0c;ins红人营销等。这种方法花钱多&#xff0c;也没太多技术含量。…

keepalived+Nginx实现高可用场景

场景说明&#xff1a; 在实际的生产项目中&#xff0c;我们对服务要实现高可用&#xff0c;这种效果可以用nginx实现&#xff1b; 但是nginx只有一台&#xff0c;若nginx的服务器宕了&#xff0c;高可用也就无法实现&#xff1b; 所以可以通过keepalived实现nginx的高可用。…

字符串中删除子串

【问题描述】编写一个程序&#xff0c;当在一个字符串中出现子串时就删除它&#xff08;字符串的字符个数不超过1000&#xff09;。 【输入形式】第一行输入一个字符串&#xff0c;第二行输入一个子串。 【输出形式】程序在下一行输出删除其中所有子串后的字符串。如果字符串…

AJAX知识点及其用法

同步&#xff1a;上一个任务结束下一个再开始 比如alert弹窗&#xff0c;登录注册流程 异步&#xff1a;按顺序开始不一定按顺序结束 比如图片加载&#xff0c;上传下载等任务 obj中&#xff1a; *type:请求方式 *url:请求地址 协议域名/IP&#xff1a;port路由 *data:参数信…