请问C#Monitor.Wait()中的虚假唤醒痛苦吗? [英] Does C# Monitor.Wait() suffer from spurious wakeups?

查看:688
本文介绍了请问C#Monitor.Wait()中的虚假唤醒痛苦吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的的Object.wait()警告不要虚假唤醒,但C#的 Monitor.wait()似乎更不用说它在所有。

Java's Object.wait() warns against "spurious wakeups" but C#'s Monitor.wait() doesn't seem to mention it at all.

看到单是如何在Linux上实现的,而Linux具有的虚假唤醒的,应该不是这个地方被记录?

Seeing how Mono is implemented on top of Linux, and Linux has spurious wakeups, shouldn't this be documented somewhere?

推荐答案

乔·达菲的的\"Concurrent编程在Windows提到了这一点(P311-312,P598)。该位是有趣:

Joe Duffy's "Concurrent Programming On Windows" mentions this (P311-312, P598). This bit is interesting:

请注意,在所有的上述实施例中,线程必须弹性的所谓虚假唤醒, - 代码使用条件变量应即使在它过早苏醒,也就是案件保持正确的活泼,受到追捧的条件已经建立了。这并不是因为实施实际上将做这样的事情(尽管像Java和Pthreads的其他平台的一些实现被称为这样做),也不是因为代码将唤醒线程有意当它是不必要的,而是由于这样的事实,有没有保证时左右已被唤醒线程将成为预定。条件变量是不公平的。这是可能的 - 甚至可能 - 另一个线程将收购相关的锁和使病情再次假的唤醒的线程有机会重新获取锁,并返回到临界区之前

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. 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.

他接着给出了一个while循环测试条件下的正常模式。

He then gives the normal pattern for a while loop testing the condition.

我会说,从这个是合理的预计, Monitor.Wait 不会的正常唤醒你过早,而且如果你绝对的知道的没有别的能改变了的条件,那么你的可能的能逃脱没有条件循环。但它的安全,包括它无论如何,以防万一你的逻辑是不准确的。

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.

这篇关于请问C#Monitor.Wait()中的虚假唤醒痛苦吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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