Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock on a variable in multiple threads

I am very new to C# and I wanted to ask if I have this situation in MULTI THREADS (pseudo code):

public class ClassA
{
     ClassB c = new ClassB();
     public void someMethod()
     {
          c.myVar = 1;
          // Some other stuff
          c.myVar = 0;
     }
}

public class ClassB
{
     internal int myVar;

     public void MethodA()
     {
        if(myVar = 1)
              myVar = 0;
     }
}

If someMethod() and MethodA() can be active in separate threads, then MethodA() could evaluate the if statement as true; but before it sets myVar = 0, someMethod() sets myVar = 0 making it incorrect to have set myVar to 0 in MethodA()!!

Basically, how do I lock myVar:

  • can I lock{} on myVar's property (set, get)
  • do I need to use Interlock (I have no experience yet of Interlock though)?
like image 301
SimpleOne Avatar asked Nov 02 '10 20:11

SimpleOne


People also ask

Can multiple threads take a lock simultaneously?

Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.

Can two threads acquire the same lock?

If a thread tries to acquire a lock currently owned by another thread, it blocks until the other thread releases the lock. At that point, it will contend with any other threads that are trying to acquire the lock. At most one thread can own the lock at a time.

Can multiple threads read the same variable?

When race conditions occur. A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.

Why are locks needed in a multi threaded program?

A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.


1 Answers

You should create a private object that will allow for locking:

private readonly object _locker = new object();

Then in your property get/set methods, lock around it:

get { lock (_locker) { return this.myVar; } }
set { lock (_locker) { this.myVar = value; } }

Make sure your method uses the lock also:

public void MethodA()
{
    lock(_locker)
    {
        if(myVar == 1)
          myVar = 0;
    }
}
like image 123
aqwert Avatar answered Sep 19 '22 18:09

aqwert