Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Joe Duffy's "Concurrent Programming On Windows" mentions this (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. 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...