c++ TerminateThread函数结束线程的危险性

一、TerminateThread强烈不建议使用,因为这个函数的执行是异步的,
你无法保证调用之后会立即退出,同时线程的堆栈均不会被销毁,而导致内存泄露。如果调用了这个函数,请确保使用WaitForSingleObject来等待线程对象的结束。

能使用TerminateThread结束线程的地方: 线程函数简单,只做简单数据处理不涉及资源分配,无动态对象。但还是需要慎用。

参考链接:https://blog.csdn.net/qq_35097289/article/details/80240702

二、调用TerminateThread杀线程的致命问题:

TerminateThread终止线程后,堆栈没有被回收(注意连栈都没有被回收)

整个进程在分配和回收内存时,占用同一把锁,如果一个线程在使用该锁时被杀死(即临死前该线程在new或delete操作中),则其他线程就无法再使用new或delete了,表现为卡住

参考MSDN:

MSDN 2005 原文:TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code and its initial stack is not deallocated. DLLs attached to the thread are not notified that the thread is terminating.

你可能感兴趣的:(C/C++,Windows编程)