开发者

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

开发者 https://www.devze.com 2023-04-02 09:37 出处:网络
Suppose I have the following C# class class MyClass { private int _i; private object _locker = new object();

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

        lo开发者_JAVA技巧ck(_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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号