How to lock a variable used in multiple threads

前端 未结 6 2271
花落未央
花落未央 2021-02-13 02:47

I have asked a question badly over here Lock on a variable in multiple threads so for clarity I am going to ask it here and hope I can ask it correctly.

classA
          


        
6条回答
  •  悲&欢浪女
    2021-02-13 03:10

    Unfortunately, the question is somewhat ambiguous about what is considered success in terms of thread safety. Thread safety just means that the operation would work correctly if multiple threads are executing.

    What seems to be missing is whether or not classA.methodA or classA.methodB needs to finish its operation with classB.myVar before either another thread calling classA.methodA(...) or classA.methodB(...). It would determine what type of locking pattern you would need.

    For example, if you need a guarantee on reading a value, it would look like the following:

    public class classA
    {
        private classB b = new classB();
    
        public void methodA()
        {
            lock (b)
            {
                // Operation without calling methodA() or methodB() 
                // Read b.myVar
                // Update b.myVar
            }
        }
    
        public void methodB()
        {
            lock (b)
            {
                // Operation without calling methodA() or methodB()
                // Read b.myVar
                // Update b.myVar
            }
        }
    }
    

    In another example, if b.myVar is some type of collection that needs to be synchronized like a cache, it would look like the following:

    public class classA
    {
        private classB b = new classB();
    
        public void methodA()
        {
            // Read b.myVar for missing collection item
    
            lock (b)
            {
                // Check for missing collection item again. If not missing, leave lock
                // Operation without calling methodA() or methodB() 
                // Read b.myVar
                // Update b.myVar with new array item
            }
        }
    
        public void methodB()
        {
            // Read b.myVar for missing collection item
            lock (b)
            {
                // Check for missing collection item again. If not missing, leave lock
                // Operation without calling methodA() or methodB() 
                // Read b.myVar
                // Update b.myVar with new array item
            }
        }
    }
    

提交回复
热议问题