We need to lock a .NET Int32 when reading it in a multithreaded code?

前端 未结 6 769
悲哀的现实
悲哀的现实 2020-12-23 23:38

I was reading the following article: http://msdn.microsoft.com/en-us/magazine/cc817398.aspx \"Solving 11 Likely Problems In Your Multithreaded Code\" by Joe Duffy

An

6条回答
  •  青春惊慌失措
    2020-12-24 00:04

    Having only 1 thread lock accomplishes nothing. The purpose of the lock is to block other threads, but it doesn't work if no one else checks the lock!

    Now, you don't need to worry about memory corruption with a 32-bit int, because the write is atomic - but that doesn't necessarily mean you can go lock-free.

    In your example, it is possible to get questionable semantics:

    example = 10
    
    Thread A:
       Add(10)
          read example (10)
    
    Thread B:
       Read()
          read example (10)
    
    Thread A:
          write example (10 + 10)
    

    which means ThreadB started to read the value of example after thread A began it's update - but read the preupdated value. Whether that's a problem or not depends on what this code is supposed to do, I suppose.

    Since this is example code, it may be hard to see the problem there. But, imagine the canonical counter function:

     class Counter {
        static int nextValue = 0;
    
        static IEnumerable GetValues(int count) {
           var r = Enumerable.Range(nextValue, count);
           nextValue += count;
           return r;
        }
     }
    

    Then, the following scenario:

     nextValue = 9;
    
     Thread A:
         GetValues(10)
         r = Enumerable.Range(9, 10)
    
     Thread B:
         GetValues(5)
         r = Enumerable.Range(9, 5)
         nextValue += 5 (now equals 14)
    
     Thread A:
         nextValue += 10 (now equals 24)
    

    The nextValue is incremented properly, but the ranges returned will overlap. The values of 19 - 24 were never returned. You would fix this by locking around the var r and nextValue assignment to prevent any other thread from executing at the same time.

提交回复
热议问题