开发者

Suspending and resuming threads in c++

My application has to suspend and resume a different process every few *microsec*s.

It works fine only sometimes it feels like it suspends the process for non-uniforms times.

I use the win API: ResumeThread and SuspendThread.

On the other hand, I tried something a little different.

I suspended the thread as usual with SuspendThread 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜