Mutual exclusion: is this safe?

No, that is not safe. If you want to ensure mutually exclusive without blocking, you can use Monitor.TryEnter.

No, that is not safe. If you want to ensure mutually exclusive without blocking, you can use Monitor. TryEnter: if (Monitor.

TryEnter(lockObj, 0)) { // got the lock! Try { // code } finally { // release the lock Monitor. Exit(lockObj); } }.

Thanks. – marijne Feb 16 '09 at 14:49 Well, you are accessing the flag outside of the lock.As it happens, you're only setting it to false, but this means you could be denying an essential thread - I can foresee problems. Since it is relatively easy to use TryEnter instead, I'd use that... – Marc Gravell?

Feb 16 '09 at 14:56.

The correctness of your mutual exclusion pattern depends on the assignment _flag=false being atomic. Imagine what would happen if the assignment could be interrupted by another thread. If intermediate results of the assignment could be interpreted as false by the test, one assignment could cause several threads to enter the critical section.

The correctness of the mutual exclusion pattern also depends on the absence of optimisations in the compiler that may rearrange the ordering of the statements. Imagine a "smart" compiler that would move the assignment _flag=false up, because _flag is not referred to in the code that is in between (and the code in between does not throw exceptions). The compiler could then optimise the part in the lock section to read if(_flag) return; Both examples of why the pattern could fail are highly speculative and I think that you are safe in assuming it works.

However, in the presence of another option that works as required, you're better off using that (see the other posts). If there are other developers in the same code, they do not need to consider whether the pattern works.

Interesting answer, thanks! I had not considered the effects of optimisation. – marijne Feb 17 '09 at 11:41.

Behind the scenes, it creates the Monitor and critical section inside a try... finally block. Private static readonly Object lockMe = new Object(); lock(lockMe) { // critical code }.

But without the other threads piling up waiting to acquire the lock. " - i.e. The OP wants it mutually exclusive but non-blocking.

– Marc Gravell? Feb 16 '09 at 15:25 That's an interesting requirement. I've never needed a locking mechanism like that.

– Anthony Mastrean Feb 16 '09 at 16:33.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions