WaitForMultipleObjects 与 CRITICAL_SECTION
我的理解是, WaitForMultipleObjects
和 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 thread 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们不可互换并且有不同的用途。
临界区是一个互斥锁。封装在关键代码中的代码块一次只能由一个线程输入。这也称为序列化,因为受保护的块是串行执行的。
WaitForMultipleObjects
函数及其各种相关函数用于阻塞,直到发出同步对象信号为止。这可能是一个事件发出信号、线程完成、进程完成、互斥体变得可用等。通常使用等待函数来确保正确处理依赖项。例如,如果计算只能在其他计算完成后才能继续,则将使用等待函数进行阻塞,直到其他计算完成为止。使用适当的等待函数而不是繁忙的自旋查找可以避免浪费时钟周期。
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.
Critical Section
是用户对象(注意 core),因此它比任何mutex
都要快(它是 core 对象,因此需要系统核心调用)。因此,CS
只能用于同步一个进程内的线程(您不能在不同进程中使用一个CS
)。WaitForMultipleObjects
使用核心对象进行同步(互斥体、事件),因此它实际上可以用于进程间同步。要以同样的方式使用
CS
,您还需要一个条件变量
(Win XP 中没有,仅在以后)。Critical Section
is user object (note core), so it is quicker than anymutex
(it is core object, so system core call is required). As a result theCS
can be used to synchronize only threads inside of one process (you cannot use oneCS
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 aconditional variable
(not in Win XP, only later).我认为 MSDN 的引用是足够的:
所以
关键部分
用于单进程同步。使用WaitForMultipleObjects
您可以执行多个进程。我将补充一点,使用
WaitForMultipleObjects
您可以等待其他事情,例如异步 I/O 函数、计时器...I think a quote from MSDN is enough:
So
Critical Sections
are for single process synchronization. WithWaitForMultipleObjects
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...