Memory Barrier by lock statement

Posted by jalalaldeen on Stack Overflow See other posts from Stack Overflow or by jalalaldeen
Published on 2010-05-16T16:16:00Z Indexed on 2010/05/16 16:20 UTC
Read the original article Hit count: 127

Filed under:
|

I read recently about memory barrier and the reordaring issue and now I have some confusion about it.

Let us have a following senario:

private object _object1 = null;

private object _object2 = null;

private bool _usingObject1 = false;

private object MyObject
{
    get 
    {
        if (_usingObject1)
        {
            return _object1;
        }
        else
        {
            return _object2;
        }
    }
    set 
    {
        if (_usingObject1)
        {
           _object1 = value;
        }
        else
        {
           _object2 = value;
        }
    }
}

private void Update()
{
    _usingMethod1 = true;
    SomeProperty = FooMethod();
    //..
    _usingMethod1 = false;
}

1- At Update method; is it always _usingMethod1 = true statement excecuted before getting or setting the property? or due reordaring issue we can not garantee that?

2- Should we use volitle like.

private volitle bool _usingMethod1 = false;

3- If we use lock; can we garantee then every statement within the lock will be excecuted in order like:

private void FooMethod()
{
    object locker = new object();
    lock (locker)
    {
        x = 1;
        y = a;
        i++;
    }
}

Thanks in advanced..

© Stack Overflow or respective owner

Related posts about c#

Related posts about memorybarrier