How can I set a min value in .Net without using a lock?

后端 未结 2 674
一个人的身影
一个人的身影 2021-01-14 06:51

I have multiple threads accessing variables. I know how to write spinlocks and use the Threading.Interlocked methods to increment etc. variables.

However, I want to

2条回答
  •  情深已故
    2021-01-14 07:37

    Here is the general pattern for simulating an interlocked operation.

    public static T InterlockedOperation(ref T location, T value)
    {
      T initial, computed;
      do
      {
        initial = location;
        computed = op(initial, value); // initial | value
      } 
      while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
      return computed;
    }
    

    The min operation is a completely different story. The issue here is that there are two memory locations in play. Furthermore, we are only interested in reading them. That means we really only need to worry about the memory barrier problem. Decorate your fields with volatile or do an explicit call to Thread.MemoryBarrier prior to computing the min.

    Edit: I missed the fact that the result of the min operation is assigned to a. You can actually use the pattern I defined above, but instead of doing computed = initial | value do computed = initial < value ? initial : value. Everything else stays the same.

提交回复
热议问题