Memory Barrier by lock statement

前端 未结 2 627
悲哀的现实
悲哀的现实 2020-12-08 03:04

I read recently about memory barriers and the reordering issue and now I have some confusion about it.

Consider the following scenario:

private objec         


        
2条回答
  •  旧时难觅i
    2020-12-08 04:00

    The volatile keyword doesn't accomplish anything here. It has very weak guarantees, it does not imply a memory barrier. Your code doesn't show another thread getting created so it is hard to guess if locking is required. It is however a hard requirement if two threads can execute Update() at the same time and use the same object.

    Beware that your lock code as posted doesn't lock anything. Each thread would have its own instance of the "locker" object. You have to make it a private field of your class, created by the constructor or an initializer. Thus:

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

    Note that there will also be a race on the SomeProperty assignment.

提交回复
热议问题