Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking a single bool variable when multithreading?

Tags:

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?

like image 673
Daniel Peñalba Avatar asked Mar 30 '12 09:03

Daniel Peñalba


People also ask

How do you lock a variable in a thread?

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

Is a bool thread-safe?

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.

How do you set a bool variable to false?

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

What is lock in multithreading C#?

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.


1 Answers

In my opinion, no, the lock is superfluous here, for two reasons:

  1. Boolean variables cannot cause assignment tearing like long for example, hence locking is not necessary.
  2. To solve the visibility problem 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.
like image 141
Tudor Avatar answered Nov 29 '22 09:11

Tudor