Non blocking locking

前端 未结 4 1555
悲&欢浪女
悲&欢浪女 2021-01-04 19:28

I want to start some new threads each for one repeating operation. But when such an operation is already in progress, I want to discard the current task. In my scenario I ne

4条回答
  •  -上瘾入骨i
    2021-01-04 20:11

    You should use Interlocked class atomic operations - for best performance - since you won't actually use system-level sychronizations(any "standard" primitive needs it, and involve system call overhead). //simple non-reentrant mutex without ownership, easy to remake to support //these features(just set owner after acquiring lock(compare Thread reference with Thread.CurrentThread for example), and check for matching identity, add counter for reentrancy) //can't use bool because it's not supported by CompareExchange private int lock;

    public bool TryLock()
    {
      //if (Interlocked.Increment(ref _inUseCount) == 1)      
      //that kind of code is buggy - since counter can change between increment return and
      //condition check - increment is atomic, this if - isn't.       
      //Use CompareExchange instead
      //checks if 0 then changes to 1 atomically, returns original value
      //return true if thread succesfully occupied lock
      return CompareExchange(ref lock, 1, 0)==0;
      return false;
    
    }
    public bool Release()
    {
      //returns true if lock was occupied; false if it was free already
      return CompareExchange(ref lock, 0, 1)==1;
    }
    

提交回复
热议问题