简体   繁体   English

C#Monitor.Wait()是否遭受虚假唤醒?

[英]Does C# Monitor.Wait() suffer from spurious wakeups?

Java's Object.wait() warns against "spurious wakeups" but C#'s Monitor.wait() doesn't seem to mention it at all. Java的Object.wait()警告“虚假的唤醒”,但C#的Monitor.wait()似乎根本没有提到它。

Seeing how Mono is implemented on top of Linux, and Linux has spurious wakeups , shouldn't this be documented somewhere? 看看Mono是如何在Linux之上实现的,并且Linux有虚假的唤醒 ,不应该在某处记录吗?

Joe Duffy's "Concurrent Programming On Windows" mentions this (P311-312, P598). Joe Duffy的“Windows上并发编程”提到了这一点(P311-312,P598)。 This bit is interesting: 这一点很有趣:

Note that in all of the above examples, threads must be resilient to something called spurious wake-ups - code that uses condition variables should remain correct and lively even in cases where it is awoken prematurely, that is, before the condition being sought has been established. 请注意,在上述所有示例中,线程必须对称为虚假唤醒的内容具有弹性 - 即使在过早唤醒的情成立。 This is not because the implementation will actually do such things (although some implementations on other platforms like Java and Pthreads are known to do so), nor because code will wake threads intentionally when it's unnecessary, but rather due to the fact that there is no guarantee around when a thread that has been awakened will become scheduled. 这不是因为实现实际上会做这样的事情(虽然已知其他平台上的某些实现,比如Java和Pthreads这样做),也不是因为代码会在不必要时故意唤醒线程,而是因为没有保证被唤醒的线程何时被安排。 Condition variables are not fair. 条件变量不公平。 It's possible - and even likely - that another thread will acquire the associated lock and make the condition false again before the awakened thread has a chance to reacquire the lock and return to the critical region. 有可能 - 甚至可能 - 另一个线程将获取相关的锁并在唤醒的线程有机会重新获取锁并返回临界区之前再次使条件为假。

He then gives the normal pattern for a while loop testing the condition. 然后他给出了测试条件的while循环的正常模式。

I would say that from this it's reasonable to expect that Monitor.Wait won't normally wake you prematurely, and that if you absolutely know that nothing else can have changed the condition then you might be able to get away without the condition loop: but that it's safer to include it anyway, just in case your logic is inaccurate. 我会说,从这一点来看,有理由期望Monitor.Wait通常不会过早地唤醒你,并且如果你完全知道没有其他任何东西可以改变条件,那么你可以在没有条件循环的情况下逃脱:但是无论如何,包括它更安全,以防你的逻辑不准确。

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

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