C++死锁解决心得

简介: 一、 概述C++多线程开发中,容易出现死锁导致程序挂起的现象。关于死锁的信息,见百度百科http://baike.baidu.com/view/121723.htm。解决步骤分为三步:1、检测死锁线程。
一、 概述
C++多线程开发中,容易出现死锁导致程序挂起的现象。

关于死锁的信息,见百度百科 http://baike.baidu.com/view/121723.htm

解决步骤分为三步:
1、检测死锁线程。
2、打印线程信息。
3、修改死锁程序。

二、 程序示例
VS2005创建支持MFC的win32控制台程序。
代码见示例代码DeadLockTest.cpp。
[cpp]   view plain copy
  1. // DeadLockTest.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "DeadLockTest.h"  
  6.   
  7. #ifdef _DEBUG  
  8. #define new DEBUG_NEW  
  9. #endif  
  10.   
  11.   
  12. // The one and only application object  
  13.   
  14. CWinApp theApp;  
  15.   
  16. using namespace std;  
  17.   
  18. CRITICAL_SECTION cs1;  
  19. CRITICAL_SECTION cs2;  
  20. CRITICAL_SECTION csprint;  
  21.   
  22. //初始化关键代码段  
  23. void InitMyCriticalSection();  
  24. //删除关键代码段  
  25. void DeleteMyCriticalSection();  
  26. //打印信息  
  27. void PrintString(const CString& strInfo);  
  28.   
  29. DWORD WINAPI Thread1(LPVOID lpParameter);  
  30. DWORD WINAPI Thread2(LPVOID lpParameter);  
  31.   
  32. int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])  
  33. {  
  34.     int nRetCode = 0;  
  35.   
  36.     // initialize MFC and print and error on failure  
  37.     if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))  
  38.     {  
  39.         // TODO: change error code to suit your needs  
  40.         _tprintf(_T("Fatal Error: MFC initialization failed\n"));  
  41.         nRetCode = 1;  
  42.   
  43.         return nRetCode;  
  44.     }  
  45.   
  46.     //初始化关键代码段  
  47.     InitMyCriticalSection();  
  48.   
  49.     //创建线程  
  50.     HANDLE hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, NULL);  
  51.     HANDLE hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, NULL);  
  52.   
  53.     //等待线程结束  
  54.     WaitForSingleObject(hThread1, INFINITE);  
  55.     WaitForSingleObject(hThread2, INFINITE);  
  56.   
  57.     //关闭线程句柄  
  58.     CloseHandle(hThread1);  
  59.     CloseHandle(hThread2);  
  60.   
  61.     //释放关键代码段  
  62.     DeleteMyCriticalSection();  
  63.   
  64.     return nRetCode;  
  65. }  
  66.   
  67. void InitMyCriticalSection()  
  68. {  
  69.     InitializeCriticalSection(&cs1);  
  70.     InitializeCriticalSection(&cs2);  
  71.     InitializeCriticalSection(&csprint);  
  72. }  
  73.   
  74. void DeleteMyCriticalSection()  
  75. {  
  76.     DeleteCriticalSection(&cs1);  
  77.     DeleteCriticalSection(&cs2);  
  78.     DeleteCriticalSection(&csprint);  
  79. }  
  80.   
  81. DWORD WINAPI Thread1(LPVOID lpParameter)  
  82. {  
  83.     for (int i = 0; i < 5; i++)  
  84.     {  
  85.         EnterCriticalSection(&cs1);  
  86.         Sleep(500);  
  87.         EnterCriticalSection(&cs2);  
  88.   
  89.         PrintString(_T("Thread1"));  
  90.   
  91.         LeaveCriticalSection(&cs2);  
  92.         LeaveCriticalSection(&cs1);  
  93.     }  
  94.   
  95.     return 1;  
  96. }  
  97.   
  98. DWORD WINAPI Thread2(LPVOID lpParameter)  
  99. {  
  100.     for (int i = 0; i < 5; i++)  
  101.     {  
  102.         EnterCriticalSection(&cs2);  
  103.         Sleep(500);  
  104.         EnterCriticalSection(&cs1);  
  105.   
  106.         PrintString(_T("Thread2"));  
  107.   
  108.         LeaveCriticalSection(&cs1);  
  109.         LeaveCriticalSection(&cs2);  
  110.     }  
  111.   
  112.     return 1;  
  113. }  
  114.   
  115. void PrintString(const CString& strInfo)  
  116. {  
  117.     EnterCriticalSection(&csprint);  
  118.     wcout<<(const TCHAR*)strInfo<<endl;  
  119.     LeaveCriticalSection(&csprint);  
  120. }  

运行DeadLockTest.exe,程序挂起。

三、 死锁检测
检测工具见《Windows核心编程》,第9章9.8.6节LockCop检测工具。
工具源码地址:http://www1.wintellect.com/Resources/Details/86

LockCop可使用vs2010编译成功。
备注:该工具使用了Windows Vista/ 7提供的WCT API,故需要在Windows Vista/ 7系统运行LockCop检测工具。

检测,挂起的DeadLockTest.exe,得到线程信息。

检测到程序挂起由死锁引起。

线程4014:等待线程772、线程4012完成。
线程772:拥有关键代码段A,等待关键代码段B(被线程4012拥有)。
线程4012:拥有关键代码段B,等待关键代码段A(被线程772拥有)。

线程772与4012互相等待,程序发生死锁现象。

四、 打印信息
为了便于查找问题,我们加上线程打印信息。
打印线程名称、线程ID以及关键代码段进入信息。

[cpp]   view plain copy
  1. DWORD WINAPI Thread1(LPVOID lpParameter)  
  2. {  
  3.     CString strThreadID = _T("");  
  4.     strThreadID.Format(_T("%d"), GetCurrentThreadId());  
  5.   
  6.     CString strPrintInfo = _T("");  
  7.   
  8.     for (int i = 0; i < 5; i++)  
  9.     {  
  10.         EnterCriticalSection(&cs1);  
  11.   
  12.         strPrintInfo = _T("");  
  13.         strPrintInfo += _T("Thread1 ");  
  14.         strPrintInfo += strThreadID;  
  15.         strPrintInfo += _T(" EnterCriticalSection(&cs1)");  
  16.   
  17.         PrintString(strPrintInfo);  
  18.   
  19.         Sleep(500);  
  20.         EnterCriticalSection(&cs2);  
  21.   
  22.         strPrintInfo = _T("");  
  23.         strPrintInfo += _T("Thread1 ");  
  24.         strPrintInfo += strThreadID;  
  25.         strPrintInfo += _T(" EnterCriticalSection(&cs2)");  
  26.   
  27.         PrintString(strPrintInfo);  
  28.   
  29.         LeaveCriticalSection(&cs2);  
  30.         LeaveCriticalSection(&cs1);  
  31.     }  
  32.   
  33.     return 1;  
  34. }  
  35.   
  36. DWORD WINAPI Thread2(LPVOID lpParameter)  
  37. {  
  38.     CString strThreadID = _T("");  
  39.     strThreadID.Format(_T("%d"), GetCurrentThreadId());  
  40.   
  41.     CString strPrintInfo = _T("");  
  42.   
  43.     for (int i = 0; i < 5; i++)  
  44.     {  
  45.         EnterCriticalSection(&cs2);  
  46.   
  47.         strPrintInfo = _T("");  
  48.         strPrintInfo += _T("Thread2 ");  
  49.         strPrintInfo += strThreadID;  
  50.         strPrintInfo += _T(" EnterCriticalSection(&cs2)");  
  51.   
  52.         PrintString(strPrintInfo);  
  53.   
  54.         Sleep(500);  
  55.   
  56.         EnterCriticalSection(&cs1);  
  57.   
  58.         strPrintInfo = _T("");  
  59.         strPrintInfo += _T("Thread2 ");  
  60.         strPrintInfo += strThreadID;  
  61.         strPrintInfo += _T(" EnterCriticalSection(&cs1)");  
  62.   
  63.         PrintString(strPrintInfo);  
  64.   
  65.         LeaveCriticalSection(&cs1);  
  66.         LeaveCriticalSection(&cs2);  
  67.     }  
  68.   
  69.     return 1;  
  70. }  

运行结果如下。


五、 死锁修改
线程互斥进行修改,Thread1与Thread2对关键代码段的进入与退出顺序改为相同。程序运行正常。
修改后线程代码。

[cpp]   view plain copy
  1. DWORD WINAPI Thread1(LPVOID lpParameter)  
  2. {  
  3.     for (int i = 0; i < 5; i++)  
  4.     {  
  5.         EnterCriticalSection(&cs1);  
  6.         Sleep(500);  
  7.         EnterCriticalSection(&cs2);  
  8.   
  9.         PrintString(_T("Thread1"));  
  10.   
  11.         LeaveCriticalSection(&cs2);  
  12.         LeaveCriticalSection(&cs1);  
  13.     }  
  14.   
  15.     return 1;  
  16. }  
  17.   
  18. DWORD WINAPI Thread2(LPVOID lpParameter)  
  19. {  
  20.     for (int i = 0; i < 5; i++)  
  21.     {  
  22.         EnterCriticalSection(&cs1);  
  23.         Sleep(500);  
  24.         EnterCriticalSection(&cs2);  
  25.   
  26.         PrintString(_T("Thread2"));  
  27.   
  28.         LeaveCriticalSection(&cs2);  
  29.         LeaveCriticalSection(&cs1);  
  30.     }  
  31.   
  32.     return 1;  
  33. }  

目录
相关文章
|
NoSQL Linux Redis
c++开发redis module问题之避免在fork后子进程中发生死锁,如何解决
c++开发redis module问题之避免在fork后子进程中发生死锁,如何解决
|
算法 NoSQL Linux
Linux C++环境下避免死锁的全面策略解析与实践指南
Linux C++环境下避免死锁的全面策略解析与实践指南
265 0
手写C/C++死锁检测
手写C/C++死锁检测
228 0
|
C++
c++多线程编程之互斥对象(锁)的使用之----死锁
一、死锁会在什么情况发生 1、假设有如下代码    mutex;   //代表一个全局互斥对象    void  A()       {           mutex.lock();           //这里操作共享数据           B();  //这里调用B方法           mutex.
1255 0
|
7月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
3月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
84 0
|
3月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
164 0
|
5月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
161 12
|
6月前
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
124 16