Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WaitForSingleObject() vs RegisterWaitForSingleObject()?

What is the advantage/disadvantage over using RegisterWaitForSingleObject() instead of WaitForSingleObject()?

The reason that I know:

  1. RegisterWaitForSingleObject() uses the thread pool already available in OS
  2. In case of the use of WaitForSingleObject(), an own thread should be polling for the event.

the only difference is Polling vs. Automatic Event? or Is there any considerable performance advantage between these?

like image 583
InnovWelt Avatar asked Sep 09 '13 08:09

InnovWelt


2 Answers

It's pretty straight-forward, WaitForSingleObject() blocks a thread. It is consuming a megabyte of virtual memory and not doing anything useful with it while it is blocked. It won't wake up and resume doing useful stuff until the handle is signaled.

RegisterWaitForSingleObject() does not block a thread. The thread can continue doing useful work. When the handle is signaled, Windows grabs a thread-pool thread to run the code you specified as the callback. The same code you would have programmed after a WFSO call. There is still a thread involved with getting that callback to run, the wait thread, but it can handle many RWFSO requests.

So the big advantage is that your program can use a lot less threads while still handling many service requests. A disadvantage is that it can take a bit longer for the completion code to start running. And it is harder to program correctly since that code runs on another thread. Also note that you don't need RWFSO when you already use overlapped I/O.

like image 104
Hans Passant Avatar answered Nov 18 '22 10:11

Hans Passant


They serve two different code models. In case with RegisterWaitForSingleObject you'll get an asynchronous notification callback on a random thread from the thread pool managed by the OS. If you can structure your code like this, it might be more efficient. On the other hand, WaitForSingleObject is a synchronous wait call blocking (an thus 'occupying') the calling thread. In most cases, such code is easier to write and would probably be less error-prone to various dead-lock and race conditions.

like image 23
avo Avatar answered Nov 18 '22 10:11

avo