前言
最近我们的程序在退出时会卡住,调查发现是在卸载dll
时死锁了。大概流程是这样的:我们的dll
在加载的时候会创建一个工作线程,在卸载的时候,会设置退出标志并等待之前开启的工作线程结束。为了研究这个经典的死锁问题,写了一个模拟程序,用到的dump
文件及示例代码参考附件。
{% note info %}
这也是几年前在项目中遇到的一个问题,我对之前的笔记进行了整理重新发布于此。
{% endnote %}
关键代码
主程序 WaitDllUnloadExe
//WaitDllUnloadExe.cpp
#include "stdafx.h"
#include "windows.h"
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE module = LoadLibraryA(".\\DllUnload.dll");
Sleep(5000);
FreeLibrary(module);
return 0;
}
DLL程序 DllUnload
// dllmain.cpp
#include "stdafx.h"
#include "process.h"
HANDLE g_hThread;
bool g_quit = false;
unsigned __stdcall procThread(void *)
{
while ( !g_quit )
{
OutputDebugStringA("procThread running.\n");
Sleep(100);
}
OutputDebugStringA("==========================procThread quitting.\n");
return 0;
}
unsigned __stdcall quitDemoProc(void *)
{
int idx = 0;
while ( idx++ < 5 )
{
OutputDebugStringA("quitDemoProc running!!!!!!!!.\n");
Sleep(100);
}
OutputDebugStringA("--------------------------------------------------quitDemoProc quitting.\n");
return 0;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case</