Suspending and resuming threads in c++
ResumeThread
and SuspendThread
.
On the other hand, I tried something a little different.
I suspended the thread as usual withSuspendThread
but when I resume it, I do like so:
while (ResumeThread(threadHandle) > 0);
and it works faster and it runs th开发者_运维技巧e other process in a uniform pace.
Why does it happen? is it possible that sometimes the thread gets suspended twice and then the ResumeThread command executes? thanks :)SuspendThread()
call does not suspend a thread instantly. It takes several time to save an execution context, so that ResumeThread()
might be called when a thread has not suspended yet. That's why while (ResumeThread(threadHandle) > 0);
works. To determine the current thread state you can call NtQueryInformationThread(), but only in NT versions of Windows.
If you have a loop in the secondary thread, you can change your synchronization with a Manual Reset Event. The primary thread should call ResetEvent()
to suspend a thread, and SetEvent()
to resume. The secondary thread every loop should call WaitForSingleObjectEx()
.
I followed Damon's suggestion, removed suspend / resume from the code and instead used a synchronization object over which my pool thread waits infinitely after completing the work and the same is signaled by my server thread after allocating work to it.
The only time I have to use suspend now is when I create the thread for the first time and after allocating work to it the thread is resumed from my server thread. The thread created is used in a thread pool over and over again to do some work.
It is working like a charm.
Thank you Damon!
Regards,
Ajay
thats the way de loop look's like
for(i=0;i<num;i++) {
while (ResumeThread(threadHandle) > 0);
ResumeThread(threadHandle)
SuspendThread(threadHandle);
}
SuspendThread
takes a few milliseconds so the while loop goes on until thread is suspended, after that, again the thread process SuspendThread
function is called, a good way to call GetProcessContext
to see EIP
精彩评论