Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple threads calling the same objects function simultaneously. Can it cause problems?

Suppose I have the following C# class

class MyClass
{
    private int _i;
    private object _locker = new object();

    public void DoSomething()
    {
        var b = 2;

        // some work that depends on b being 2

        lock(_locker)
        {
            _i = 3;
        }

        // some more work

        b = -1;

        // some more work
    }
}

And I use it this way,

//Usage:

var myobject = new MyClass();
new Thread(new ThreadStart(() => myobject.DoSomething())).Start();
new Thread(new ThreadStart(() => myobject.DoSomething())).Start();

Can the following sequence happen?

Thread 1 is halfway through its work.
Thread 2 just starts. Sets b = 2. 
Thread 1 sets b = -1. 
Thread 2 is confused because it expected b to be 2 but its -1.

The important point is that b is a local variable. Will the two threads get access to the same instance of b? I understand that for the instance variable _i, this will happen. Hence the lock construct for that. But am not sure whether I need to do locking for local variables as well.

like image 711
Amith George Avatar asked Sep 03 '11 15:09

Amith George


People also ask

What happens when multiple threads call the same function?

There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.

What is the problem when multiple threads work on same object?

both threads will be writing to same memory area, so yes, it'll be overwritten.

Can multiple threads use the same object?

Because all threads share the same heap, and the heap is where all instance variables are stored, multiple threads can attempt to use the same object's instance variables concurrently.

When multiple threads call the same method on the same object at the same time its known as a?

Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java.


1 Answers

The local variable will be put on the stack when a caller enters the method DoSomething(). Each thread operates on a separate stack and will get its own unique local variable.

This part from Wikipedia for thread local storage applies to C# threading as well:

In other words, data in a static or global variable is normally always located at the same memory location, when referred to by threads from the same process. Variables on the stack however are local to threads, because each thread has its own stack, residing in a different memory location.

like image 141
BrokenGlass Avatar answered Nov 15 '22 11:11

BrokenGlass