Recently I have seen this code in a WebSite, and my question is the following:
private bool mbTestFinished = false; private bool IsFinished() { lock( mLock ) { return mbTestFinished; } } internal void SetFinished() { lock( mLock ) { mbTestFinished = true; } }
In a multithread environment, is really necessary to lock the access to the mbTestFinished
?
Use the lock keyword to guard code that can be executed simultaneously by more than one thread. public class ClassA { private ClassB b = new ClassB(); public void MethodA() { lock (b) { // Do anything you want with b here. } } public void MethodB() { lock (b) { // Do anything you want with b here. } } }
None of these are thread-safe. The thread that calls the getter will always read a stale value. How stale it is depends on the processor and the optimizer.
To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.
In my opinion, no, the lock is superfluous here, for two reasons:
long
for example, hence locking is not necessary.volatile
is enough. It's true that the lock
introduces an implicit fence, but since the lock
is not required for atomicity, volatile
is enough.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With