# thread_watchdog **Repository Path**: emtx/thread_watchdog ## Basic Information - **Project Name**: thread_watchdog - **Description**: linux应用往往存在多线程,但线程卡死的时候应用无法监测,所以写了个线程看门狗监测着线程的卡死状态,异常时kill掉应用。 - **Primary Language**: C - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 2 - **Created**: 2021-03-20 - **Last Updated**: 2025-09-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # thread_watchdog #### 介绍 linux应用往往存在多线程,但线程卡死的时候应用无法监测,所以写了个线程看门狗监测着线程的卡死状态,异常时kill掉应用。 **优化特性:** - ✅ 线程安全:使用互斥锁保护,支持多线程并发调用 - ✅ 性能优化:使用尾指针提高链表插入效率 - ✅ 错误处理:完善的参数检查和内存分配失败处理 - ✅ 内存管理:提供资源清理函数,避免内存泄漏 - ✅ 代码规范:改进变量命名和代码注释 #### 安装教程 把thread_watchdog.c 与 thread_watchdog.h文件复制到项目工程中,在需要使用此功能的xxx.c文件里引用头文件。 **编译时链接pthread库:** ```bash gcc -o your_program your_program.c thread_watchdog.c -lpthread ``` #### 使用说明 **线程中使用方法:** ``` c // 头文件 #include "thread_watchdog.h" static void* xxx_handleThread(void* arg) { // 定义 threadWd *pthreadWd = NULL; // 创建线程看门狗节点 threadWd_Create(&pthreadWd); if (pthreadWd == NULL) { // 创建失败,处理错误 return NULL; } while (1) { // 喂狗 threadWd_FeedDog(pthreadWd); /* 用户的线程功能实现 */ /* 用户的线程功能结束 */ } // 线程功能结束,删除线程看门狗节点 threadWd_Exit(&pthreadWd); return NULL; } ``` **主进程中使用:** ``` c // 头文件 #include "thread_watchdog.h" #include // 信号处理函数,用于优雅退出 void signal_handler(int sig) { threadWd_Cleanup(); // 清理资源 exit(0); } int main(int argc, char *argv[]) { // 注册信号处理函数 signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); // ... 启动其他线程 ... while (1) { // 监测各个线程看门狗的喂狗情况 threadWd_Check(); // 延时 // 注意:该延时时间必须大于各个线程每一次喂狗所用的时间,不然进程会不断自杀 sleep(5); } // 程序退出前清理资源 threadWd_Cleanup(); return 0; } ``` #### API 说明 - `threadWd_Create(threadWd **pp)`: 创建线程看门狗节点,线程安全 - `threadWd_FeedDog(threadWd *p)`: 喂狗操作,标记线程为活跃状态,线程安全 - `threadWd_Exit(threadWd **pp)`: 删除线程看门狗节点,线程安全 - `threadWd_Check(void)`: 检查所有线程看门狗状态,发现异常时调用exit(-1),线程安全 - `threadWd_Cleanup(void)`: 清理所有资源,程序退出前调用,线程安全 #### 特技 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md 2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) 6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)