std :: condition_variable :: notify_one()调用几次没有上下文切换 [英] std::condition_variable::notify_one() called several times without context switching

查看:1347
本文介绍了std :: condition_variable :: notify_one()调用几次没有上下文切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例中有多少等待线程将被唤醒:

How many waiting threads will wake up in this example:

第一个线程

void wakeUp2Threads()
{
    std::unique_lock<std::mutex> lock(condvar_mutex);

    condvar.notify_one();
    condvar.notify_one();
}

第二个线程

{
    std::unique_lock<std::mutex> lock(condvar_mutex);

    condvar.wait(lock); <- 2nd thread has entered here before 1st thread entered wakeUp2Threads.
}

第三线程

{
    std::unique_lock<std::mutex> lock(condvar_mutex);

    condvar.wait(lock); <- 3rd thread has entered here before 1st thread entered wakeUp2Threads.
}

有任何保证在这个例子中,两个通知都会被传递到不同的线程,不是相同的线程几次?

Is there any guarantee that in this example both notifications will be delivered to different threads, not the same thread several times?

我notify_one是什么意思:

I.e what does notify_one() mean:

1) notify one thread, no matter has it been already notified (but has not been woken up yet), or not. (* see note)
or
2) notify one thread, but only this one, which has not been notified yet.

(*)注意! 等待线程已经被通知过去的某个地方,唤醒,做了一些东西,并再次输入condvar.wait() - 当然,在这种情况下,几个notify_one()例程可以一遍又一遍地唤醒同一个线程。

(*) Pay attention! I'm not talking here about scenario "waiting thread had already been notified somewhere in the past, woken up, done some stuff and entered condvar.wait() again" - of course, in this case several notify_one() routines can wake up the same thread over and over again.

我在谈论另一种情况

notify_one等待线程关于唤醒,但是在等待线程已经接收到时隙形式的内核调度器并继续执行之前 - 另一个notify_one()已经被再次调用。 是否可能此第二个通知会再次传递到同一个主题中,但尚未从第一次通知中被唤醒?

notify_one() has notified waiting thread about wake-up, but BEFORE this waiting thread has received time slot form the kernel scheduler and continued execution - another notify_one() has been called again. Is it possible this second notification will be delivered to the same thread again, while it hasn't been woken up from first notification yet?

推荐答案

notify_one 以原子方式调用一个线程。这意味着第二次调用时,它不能解除阻塞同一个线程,因为它不再被阻塞。

The notify_one call atomically unblocks one thread. That means that when called a second time it can't unblock the same thread as it's no longer blocked.

这在标准中在30.5 / 3和30.5 .1 / 7。

This is specified in the standard at section 30.5/3 and 30.5.1/7.

这篇关于std :: condition_variable :: notify_one()调用几次没有上下文切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆