WaitForMultipleObjects vs CRITICAL_SECTION
What I understand is that both WaitForMultipleObjects
and CRITICAL_SECTION
are meant to wait for threads to complete. And both of them being described as process and thr开发者_开发技巧ead synchronization mechanisms between threads. Can they be used interchangeably if they are meant to achieve the same goal? If not then what is the difference between them?
They are not interchangeable and serve different purposes.
A critical section is a mutex. Blocks of code wrapped in a critical can be entered by one thread at a time. This is also known as serialization because protected blocks are executed serially.
The WaitForMultipleObjects
function and its various relatives are used to block until a synchronisation object is signaled. This could be an event becoming signaled, a thread completing, a process completing, a mutex becoming available, etc.
Typically wait functions are used to ensure dependencies are correctly handled. For example, if a calculation can only proceed when other calculations have completed, a wait function will be used to block until those other calculations have completed. Using a proper wait function rather than a busy spin look avoids wasting clock cycles.
I think a quote from MSDN is enough:
A critical section object provides synchronization similar to that provided by a mutex object, except that a critical section can be used only by the threads of a single process. Event, mutex, and semaphore objects can also be used in a single-process application, but critical section objects provide a slightly faster, more efficient mechanism for mutual-exclusion synchronization (a processor-specific test and set instruction).
So Critical Sections
are for single process synchronization. With WaitForMultipleObjects
you can sinc multiple processes.
I'll add that with WaitForMultipleObjects
you can wait for other things, like for example async I/O functions, timers...
Critical Section
is user object (note core), so it is quicker than any mutex
(it is core object, so system core call is required). As a result the CS
can be used to synchronize only threads inside of one process (you cannot use one CS
in different processes).
WaitForMultipleObjects
uses core objects for synchronizing (mutexes, events) so it can be actually used for interprocess synchronization.
To use CS
in the same way you would also need a conditional variable
(not in Win XP, only later).
精彩评论