gpt4 book ai didi

windows - 是否需要在 CPU 上安排等待 Windows 事件的线程从 sleep 中唤醒?

转载 作者:可可西里 更新时间:2023-11-01 10:29:46 24 4
gpt4 key购买 nike

最好用一个例子来描述我的问题:

  1. 我们通过 CreateEvent 创建一个 Windows 事件句柄,manualReset 为 FALSE。
  2. 我们创建了 4 个线程。确保它们都开始运行并等待 WaitForSingleObject 的上述事件。
  3. 在主线程中,在 for 循环中,我们通过 SetEvent 向该事件发出 4 次信号。比如:

    for (int i = 0; i < 4;++i)::SetEvent(event);

我的问题是,我们可以说所有这 4 个线程一定会从等待此事件中唤醒吗?

根据我对 Windows Event 的理解,答案是肯定的。因为当事件被设置时,总是有一个线程在等待它。

但是,我在 MSDN 上读到“设置已设置的事件无效”。由于等待线程可能没有机会在循环中主线程设置事件时运行。他们是否仍能收到通知并将事件重置为未发出信号?如果事件没有被重置,那么循环中后面的SetEvent显然是没有用的。

或者操作系统内核知道当一个事件被设置时应该通知哪个线程,如果有一个等待线程就立即重置这个事件。所以等待线程不需要被调度来将事件重置为未发出信号?

欢迎任何澄清或引用。谢谢。

最佳答案

Because when the event is set, there is always a thread waiting for it.

不,你不知道。就在 NtWaitForSingleObject 系统调用之前,线程可能由于某种原因无限期挂起。

Since the waiting threads probably do not get a chance to run while main thread setting event in the loop.

如果一个线程正在等待一个对象,它根本不会运行 - 这就是能够阻塞同步对象的全部意义。

Can they still be notified and reset the event to nonsignaled? If the event is not reset, the following SetEvent in the loop is obviously useless.

设置事件的线程是将信号状态重置回 0 的线程,而不是被唤醒的线程。当然,如果没有线程在等待,则信号状态不会被重置。

Or the OS kernel knows which thread should be notified when an event is set, and reset this event immediately if there is a waiting thread.

是的,内核确实知道。每个调度程序对象都有一个等待列表,当一个线程等待一个对象时,它会将一个等待 block 推送到该列表。

关于windows - 是否需要在 CPU 上安排等待 Windows 事件的线程从 sleep 中唤醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3490939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com