TerminateThread 导致LoadLibary 死锁

探讨了在Windows环境下,TerminateThread函数不当使用可能导致的线程卡死问题,特别是当目标线程持有临界区或正在执行特定内核调用时,会引发资源锁无法释放,进而影响整个进程状态。

运行此代码,a2线程会卡死,因为在LoadLibrary过程中会有一个临界区被占用,如果正好是这个时候此线程被TerminateThread终止,那么所有的loadlibrary及其他使用此锁的线程都会进入一个无限等待这个锁释放的状态。所以不光是自己实现的锁要小心,系统某些API也要小心,因为其内部也有同步的逻辑。

原因是(引自MSDN):

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

  • If the target thread owns a critical section, the critical section will not be released.
  • If the target thread is allocating memory from the heap, the heap lock will not be released.
  • If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
  • If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.

#include <windows.h>
#include <stdio.h>

DWORD WINAPI a1(LPVOID lp)
{
    do 
    {
        HMODULE h = LoadLibraryExW(L"Wtsapi32.dll",0,0);
        Sleep(1);
        FreeLibrary(h);
    } while (1);
    return 0;
}

DWORD WINAPI a2(LPVOID lp)
{
    int i = 0;
    do
    {
        HMODULE h = LoadLibraryExW(L"Wtsapi32.dll",0,0);
        Sleep(1);
        FreeLibrary(h);

        printf("\r%d", i++);
    } while (1);
    return 0;
}

DWORD WINAPI a3(LPVOID lp)
{
    do
    {
        HANDLE h = CreateThread(0, 0, a1, 0, 0, 0);
        Sleep(200);
        TerminateThread(h,0);
    } while (1);
    return 0;
}

int main(int argc ,char *argv[])
{
    CloseHandle(CreateThread(0, 0, a3, 0, 0, 0));
    CloseHandle(CreateThread(0, 0, a2, 0, 0, 0));

    do 
    {
        Sleep(10000);
    } while (1);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值