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

后端 未结 2 676
一个人的身影
一个人的身影 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:21

    If you don't anticipate a great deal of contention then perhaps something like this? (If there's likely to be a lot of contention then a plain lock might well be more efficient.)

    int original;    // assuming here that a is an int
    do
    {
        original = a;
    } while (Interlocked.CompareExchange(ref a, original | 10, original) != original)
    

提交回复
热议问题