简体   繁体   English

为什么我们需要事件来同步线程?

[英]Why do we need events to synchronize threads?

例如,如果一次仅一个线程可以访问一个Critical Section ,为什么我们需要Events来同步2个线程以对其进行读写?

There is some overlap in how they can be used, but there are also some unique features to both: 它们的使用方式有些重叠,但是两者都有一些独特的功能:

  1. Critical sections cannot be used across processes, whereas events can. 关键部分不能跨流程使用,而事件可以。
  2. A single manual-reset event can be used to release multiple threads at once. 单个手动重置事件可用于一次释放多个线程。 A critical section cannot. 关键部分不能。
  3. Events are compatible with WaitForSingleObject() et al, whereas critical sections aren't. 事件与WaitForSingleObject()等兼容,而关键部分则不兼容。
  4. A thread can wait on multiple events with WaitForMultipleObjects[Ex]() , but it can only wait for a single critical section (using a different API). 线程可以使用WaitForMultipleObjects[Ex]()等待多个事件,但是它只能等待单个关键部分(使用其他API)。

and so on. 等等。

They are not really in direct competition; 他们并不是真正的直接竞争者。 it's best to think of them as being complementary to each other. 最好将它们视为彼此互补

Mutexes are somewhere in the middle. 互斥体位于中间。 For further discussion, see What is the difference between mutex and critical section? 有关进一步的讨论,请参见互斥与关键部分有什么区别?

Events have a SetEvent function which lets it be used as a signal. 事件具有SetEvent函数,可将其用作信号。 When one thread has finished reading a file or filling a buffer, for example, it can SetEvent to get a different thread started on the next processing step for that data. 例如,当一个线程完成读取文件或填充缓冲区时,它可以使用SetEvent在下一个处理该数据的步骤上启动另一个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM