TerminateThread可能导致程序崩溃

DWORD __stdcall mythread(void* )
{
    while( true )
    {
        char* p = new char[1024];

        delete p;
    }
}


int _tmain(int argc, _TCHAR* argv[])
{

    HANDLE h = CreateThread(NULL, 0, mythread, NULL, 0, NULL);

    Sleep(1000);

    TerminateThread(h, 0);
    h = NULL;

    char* p = new char[1024]; //这里会死锁,过不去

    delete p;

    return 0;
}

    为什么死锁呢?new操作符用的是小块堆,整个进程在分配和回收内存时,都要用同一把锁。如果一个线程在占用该锁时被杀死(即临死前该线程在new或delete操作中),其他线程就无法再使用new或delete了,表现为hang住。

    《核心编程》里明确提醒不要TerminateThread,但原因并不是血淋淋滴。今天发现的这个bug印证了此书的价值。

    另注:许多临时的网络操作经常用TerminateThread,作为网络不通时的退出机制,以后要改改了。比如让该线程自生自灭,自行退出。

 

    可能引发的问题包括: 1 If the target thread owns a critical section, the critical section will not be released. (未释放互斥区,造成死锁) 2 If the target thread is allocating memory from the heap, the heap lock will not be released. (未释放堆分配锁,造成死锁) 3 If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent. (在执行内核函数时退出,造成该线程所在进程状态不确定,程序可能崩溃) 4 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. (在使用DLL时退出,造成DLL被销毁,其他使用该DLL得程序可能出现问题!)

在Windows操作系统上,如果你想关闭特定进程中的一条线程,通常需要通过一些底层API,如`CreateThread`, `WaitForSingleObject`, 或 `TerminateThread` 等。以下是基本步骤的一个示例: 1. **获取进程和线程ID**: - 使用 `OpenProcess` API 获取你要操作的进程句柄。 - 如果你想操作的是已经存在的线程,则可以使用 `OpenThread` 获取该线程句柄;如果不清楚线程ID,可以先使用 `EnumThreadWindows` 来查找。 2. **获取线程上下文**: - 使用 `GetThreadContext` 函数从线程获取其当前的上下文信息。 3. **终止线程**: - 使用 `TerminateThread` 函数传入线程句柄和终止状态(0通常表示强制结束)。 ```c++ #include <windows.h> // 示例代码,假设已经有了进程和线程句柄 HANDLE hThread = ...; DWORD dwThreadId = ...; if (hThread != INVALID_HANDLE_VALUE) { // 获取线程上下文 CONTEXT context; if (!GetThreadContext(hThread, &context)) { // 处理错误... } // 设置上下文中必要的信息,例如线程标志(SetThreadState)或中断状态 // 然后终止线程 context.TlsIndex = 0; // 取消 TLS 使用 if (!TerminateThread(hThread, 0)) { // 处理错误... } } ``` 注意:这是一项高级操作,不当使用可能导致程序崩溃或系统不稳定,因此通常只有在必要且理解风险的情况下才会进行。同时,直接强制终止线程可能导致数据丢失或未清理的状态,所以在实际应用中可能需要配合其他手段处理资源释放。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值