How to easy make this counter property thread safe?

前端 未结 5 2333
陌清茗
陌清茗 2021-02-20 08:31

I have property definition in class where i have only Counters, this must be thread-safe and this isn\'t because get and set is not in same lock, How t

5条回答
  •  难免孤独
    2021-02-20 09:23

    What exactly are you trying to do with the counters? Locks don't really do much with integer properties, since reads and writes of integers are atomic with or without locking. The only benefit one can get from locks is the addition of memory barriers; one can achieve the same effect by using Threading.Thread.MemoryBarrier() before and after you read or write a shared variable.

    I suspect your real problem is that you are trying to do something like "DoneCounter+=1", which--even with locking--would perform the following sequence of events:

      Acquire lock
      Get _DoneCounter
      Release lock
      Add one to value that was read
      Acquire lock
      Set _DoneCounter to computed value
      Release lock
    

    Not very helpful, since the value might change between the get and set. What would be needed would be a method that would perform the get, computation, and set without any intervening operations. There are three ways this can be accomplished:

    1. Acquire and keep a lock during the whole operation
    2. Use Threading.Interlocked.Increment to add a value to _Counter
    3. Use a Threading.Interlocked.CompareExchange loop to update _Counter

    Using any of these approaches, it's possible to compute a new value of _Counter based on the old value, in such a fashion that the value written is guaranteed to be based upon the value _Counter had at the time of the write.

提交回复
热议问题