解决方案

(转载)线程天敌TerminateThread与SuspendThread

seo靠我 2023-09-24 22:33:46

转载自:http://blog.csdn.net/magictong/article/details/6304439

线程天敌TerminateThread与SuspendThread

作者:童磊(magSEO靠我ictong)

目的:不是演示TerminateThread和SuspendThread的原理而是希望能在自己的程序中摒弃它们。

一、不使用TerminateThread的N条理由(先YY一下)

1、如果使SEO靠我用TerminateThread,那么在拥有线程的进程终止运行之前,系统不会撤销该线程的执行堆栈。原因是:如果其它正在执行的线程去引用被强制撤销的线程的堆栈上的值,那么其它的线程就会出现访问违规的问题SEO靠我

2、如果线程正在进行堆分配时被强行撤销,可能会破坏堆,造成堆锁没有释放,如果这时其他线程进行堆分配就会陷入死锁。

3、来之MSDN的血淋淋的警告:

a. If the target thread ownSEO靠我s a critical section, the critical section will not be released.(如果目标线程持有着一个临界区(critical section),这临SEO靠我界区将不会被释放。)

b. If the target thread is allocating memory from the heap, the heap lock will not be releSEO靠我ased. (如果目标线程正在堆里分配内存,堆锁(heap lock)将不会被释放。)

c. If the target thread is executing certain kernel32 calSEO靠我ls when it is terminated, the kernel32 state for the threads process could be inconsistent. (如果目标线程在SEO靠我结束时调用了某些kernel32,会造成kernel32的状态不一致。)

d. If the target thread is manipulating the global state of a shSEO靠我ared DLL, the state of the DLL could be destroyed, affecting other users of the DLL. (如果目标线程正在更改一个共享SEO靠我DLL的全局状态,这个共享DLL的状态可能会被破坏,影响到其他的正在使用这个DLL库的线程。

4、看来,TerminateThread作为终止一个线程的最后的杀招,微软也是不建议大家使用的。但是TermSEO靠我inateThread完全无用么?一般说来确实如此,但是如果你非常清楚你的线程在干什么,并且能够通过代码使线程在TerminateThread的时候优雅的结束,那么你可以用,但是你真的清楚么?在一个大SEO靠我型的工程项目中,试想,拥有10个线程、3个临界区、3个事件触发器的程序中,开发者能清楚线程在任何时刻都在干嘛么?

5、也许结束一个线程最可靠的方法就是确定这个线程不休眠无限期的等待下去。一个支持可以被要SEO靠我求停止的线程,它必须定期的检查看它是否被要求停止或者如果它在休眠的话看它是否能够被唤醒。支持这两个情况最简单的的方法就是使用同步对象,这样应用程序的主线程和工作中的线程能互相沟通。当应用程序希望关闭线SEO靠我程时,只要设置这个同步对象,等待线程退出。之后,线程把这个同步对象作为它周期性监测的一部分,定期检查,或者如果这个同步对象的状态改变的话,就可以执行清理操作并退出了。

二、简单的演示例子

TerminatSEO靠我eThread:

void CThreadDeadlocksDlg::OnBnClickedBtnTerminatethread()

{

HANDLE hThread = ::CreateThread(NUSEO靠我LL, 0, TerminateThreadHandle, NULL, 0, NULL);

         Sleep(1000);

         ::TerminateThread(hThread, 0);

hThread = NULSEO靠我L;

         char* p = new char[4096];

         delete p;

         return;

}

// 一个循环分配内存的线程

DWORD __stdcall CThreadDeadlocksDlg::TermiSEO靠我nateThreadHandle(void* )

{

         while(1)

         {

                   char* p = new char[4096];

                   delete p;

         }

}

看一下callstack和locks情况,就比较清楚了。

0:SEO靠我000> !locks

CritSec ntdll!LdrpLoaderLock+0 at 7c99e178

LockCount          0

RecursionCount     1

OwningTSEO靠我hread       55c

EntryCount         1

ContentionCount    1

*** Locked

CritSec +3b0608 at 003b0608

LockCountSEO靠我          2

RecursionCount     0

OwningThread       0

EntryCount         2

ContentionCount    2

*** LockeSEO靠我d

0:000> ~* kb

.  0  Id: 1540.12ac Suspend: 1 Teb: 7ffdf000 Unfrozen

ChildEBP RetAddr  Args to Child             

001SEO靠我2f57c 7c92df5a 7c93ac7b 00000110 00000000 ntdll!KiFastSystemCallRet

0012f580 7c93ac7b 00000110 000000SEO靠我00 00000000 ntdll!ZwWaitForSingleObject+0xc

0012f608 7c921046 003b06087c930dd0 003b0608 ntdll!RtlpWaitSEO靠我ForCriticalSection+0x132

0012f610 7c930dd0 003b0608 00001000 00000000 ntdll!RtlEnterCriticalSection+0SEO靠我x46

0012f83c 78134d83 003b0000 00000000 00001000 ntdll!RtlAllocateHeap+0x2f0

0012f85c 783095c4 0000100SEO靠我0 0012fe90 00000114 MSVCR80!malloc+0x7a [f:/dd/vctools/crt_bld/self_x86/crt/src/malloc.c @ 163]

SuspeSEO靠我ndThread也有同样的问题(SuspendThread本身也是比较暴力的):

http://blog.csdn.net/magictong/archive/2009/05/08/4161571.asSEO靠我px这里讲解了一个使用SuspendThread造成主线程LoadLibrary里面hang的例子。

void CThreadDeadlocksDlg::OnBnClickedBtnSuspendthrSEO靠我ead()

{

         HANDLE hThread = ::CreateThread(NULL, 0, SuspendThreadHandle, NULL, 0, NULL);

         Sleep(1000);

::SusSEO靠我pendThread(hThread);

         hThread = NULL;

         char* p = new char[4096];

         delete p;

         return;

}

// 一个会被挂起的线程

DWORD __stdSEO靠我call CThreadDeadlocksDlg::SuspendThreadHandle(void* )

{

         while(1)

         {

                   char* p = new char[4096];

                   delete p;

         }

}

0SEO靠我:000> !locks

CritSec ntdll!LdrpLoaderLock+0 at 7c99e178

LockCount          0

RecursionCount     1

OwningSEO靠我Thread       1fdc

EntryCount         2

ContentionCount    2

*** Locked

CritSec +3b0608 at 003b0608

LockCoSEO靠我unt          2

RecursionCount     1

OwningThread       1844

EntryCount         2

ContentionCount    2

***SEO靠我 Locked

.  0  Id: 1a48.1900 Suspend: 1 Teb: 7ffdf000 Unfrozen

ChildEBP RetAddr  Args to Child             

0012f57c SEO靠我7c92df5a 7c93ac7b 00000108 00000000 ntdll!KiFastSystemCallRet

0012f580 7c93ac7b 00000108 00000000 000SEO靠我00000 ntdll!ZwWaitForSingleObject+0xc

0012f608 7c921046 003b0608 7c930dd0 003b0608 ntdll!RtlpWaitForCSEO靠我riticalSection+0x132

0012f610 7c930dd0 003b0608 00001000 00000000 ntdll!RtlEnterCriticalSection+0x46

0SEO靠我012f83c 78134d83 003b0000 00000000 00001000 ntdll!RtlAllocateHeap+0x2f0

0012f85c 783095c4 00001000 00SEO靠我12fe90 000000f8 MSVCR80!malloc+0x7a

   2  Id: 1a48.1844 Suspend: 2 Teb: 7ffdd000 Unfrozen

ChildEBP RetAddSEO靠我r  Args to Child

012afe88 7c93080b 003b0000 003b8638 012aff40 ntdll!RtlpCoalesceFreeBlocks+0x373

012afSEO靠我f5c 78134c39 003b0000 00000000 003bc750 ntdll!RtlFreeHeap+0x2e9

012affa8 004014b0 003bc750 00001000 7SEO靠我c80b729 MSVCR80!free+0xcd

012affb4 7c80b729 00000000 74680000 003a0043 ThreadDeadlocks!CThreadDeadlocSEO靠我ksDlg::SuspendThreadHandle+0x10

012affec 00000000 004014a0 00000000 00000000 kernel32!BaseThreadStartSEO靠我+0x37

三、常驻进程里面遇到的问题

         当然实际coding的过程不会像上面的代码那么暴力,但是就不会有问题了吗?当然不是的,只是碰到的概率降低了而已,问题依然存在(没有PDB了,杯具)。

第一个dmp:

.SEO靠我  0  Id: e50.a20 Suspend: 1 Teb: 7ffdf000 Unfrozen

ChildEBP RetAddr  Args to Child             

WARNING: Stack unwiSEO靠我nd information not available. Following frames may be wrong.

0012fc08 77962148 00000000 00000000 1000SEO靠我0000 ntdll!KiFastSystemCallRet

0012fc30 7798c908 77a07340 7793cf13 0012fdb0 ntdll!EtwEventEnabled+0xdSEO靠我9

0012fc70 75b588bc 10000000 00000000 0012fd60 ntdll!LdrUnloadDll+0x2a

0012fc80 0041dd09 10000000 0041SEO靠我e0b6 00000401 KERNELBASE!FreeLibrary+0x82

0012fd60 76a5c5e7 0041d530 00370524 00000401 TSVulFWMan+0x1SEO靠我dd09

0012fdd8 76a54f0e 00000000 0041d530 00370524 USER32!gapfnScSendMessage+0x2cf

0012fe34 76a54f7d 00SEO靠我6ffb98 00000401 00000000 USER32!GetScrollBarInfo+0xfd

0012fe5c 77976fee 0012fe74 00000018 0012ff78 USSEO靠我ER32!GetScrollBarInfo+0x16c

0012fea8 0041d4eb 0012fecc 00000000 00000000 ntdll!KiUserCallbackDispatchSEO靠我er+0x2e

0012ff88 76233c45 7ffdd000 0012ffd4 779937f5 TSVulFWMan+0x1d4eb

0012ff94 779937f5 7ffdd000 779SEO靠我3ccb7 00000000 kernel32!BaseThreadInitThunk+0x12

0012ffd4 779937c8 00426dfb 7ffdd000 00000000 ntdll!RSEO靠我tlInitializeExceptionChain+0xef

0012ffec 00000000 00426dfb 7ffdd000 00000000 ntdll!RtlInitializeExcepSEO靠我tionChain+0xc2

         第二个dmp:

   0  Id: f54.3e8 Suspend: 1 Teb: 7ffde000 Unfrozen

ChildEBP RetAddr  Args to ChildSEO靠我

WARNING: Stack unwind information not available. Following frames may be wrong.

0012f750 77962148 000SEO靠我00000 00000000 00220000 ntdll!KiFastSystemCallRet

0012f778 7795fc7f 00220138 7793b612 0000003f ntdll!SEO靠我EtwEventEnabled+0xd9

0012f854 77985ae0 00000041 00000050 002201d4 ntdll!RtlFreeThreadActivationContexSEO靠我tStack+0x480

0012f8d8 764c9d45 00220000 00000000 00000041 ntdll!wcsnicmp+0x1e4

0012f8f8 74b7ebb5 00000SEO靠我041 0012fdc0 00000000 msvcrt!malloc+0x57

“SEO靠我”的新闻页面文章、图片、音频、视频等稿件均为自媒体人、第三方机构发布或转载。如稿件涉及版权等问题,请与 我们联系删除或处理,客服邮箱:html5sh@163.com,稿件内容仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同 其观点或证实其内容的真实性。

网站备案号:浙ICP备17034767号-2