650 Subj : Re: [.NET] Lock Object To : comp.programming.threads From : Joe Seigh Date : Fri Sep 23 2005 11:56 am Cool Guy wrote: > In the following, is accessing /fooLock/ thread-safe? > > class Test > { > readonly object fooLock = new Object(); > > public void A() { > lock (fooLock) { // could we read wrong value of /fooLock/ here? > // do something > } > } > > public void B() { > lock (fooLock) { // could we read wrong value of /fooLock/ here? > // do something > } > } > } > I'm not familiar with .NET so I'll have to extrapolate from Java. > Or must /fooLock/ be volatile? No, but it would be cleaner if it was initialized in the ctor if the readonly attribute allowed that. > > Consider that several threads, which may run Test.A() and/or Test.B(), may > already be running before /fooLock/ gets assigned. It should be taken care of by object initialization. > > If accessing it *is* thread-safe, what makes it so? The 'readonly' > modifier, the fact that it's read in a 'lock' statement ... something else? The fact that you're using lock. The readonly is only to prevent you from changing the lock object on the fly which would be a bad thing since you could have some method calls using the old lock object while some others used the new lock object. You don't need readonly but you'd have to remember to not change the lock object in your implementation. -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. . 0