递减原子计数器 - 但在<only>一定条件下

Decrement atomic counter - but <only> under a condition

本文关键字:gt only 条件下 lt 计数器 但在      更新时间:2023-10-16

我想在这行实现一些东西:

        inline void DecrementPendingWorkItems()
        {
            if(this->pendingWorkItems != 0) //make sure we don't underflow and get a very high number
            {
                ::InterlockedDecrement(&this->pendingWorkItems);
            }
        }

如何做到这一点,使两个操作作为一个块都是原子操作,而不使用锁?

您只需检查InterlockedDecrement()的结果,如果它恰好为负(或者<=0,如果更可取),则通过调用InterlockedIncrement()来撤消递减。在其他适当的代码中,这应该很好。

最简单的解决方案就是在整个部分使用互斥(以及用于对this->pendingWorkItems的所有其它接入)。如果有的话原因是这是不可接受的,那么你可能需要比较交易所:

void decrementPendingWorkItems()
{
    int count = std::atomic_load( &pendingWorkItems );
    while ( count != 0
            && ! std::atomic_compare_exchange_weak( 
                    &pendingWorkItems, &count, count - 1 ) ) {
    }
}

(这假设pendingWorkItems具有类型std::atomic_int。)

有一种东西叫做"SpinLock"。这是一个非常轻量级的同步。

这就是想法:

//
//    This lock should be used only when operation with protected resource
//  is very short like several comparisons or assignments.
//
class SpinLock
{
 public:
      __forceinline SpinLock() { body = 0; }
      __forceinline void Lock()
           {
             int spin = 15;
             for(;;) {
               if(!InterlockedExchange(&body, 1)) break;
               if(--spin == 0) { Sleep(10); spin = 29; }
             }
           }
      __forceinline void Unlock() { InterlockedExchange(&body, 0); }
 protected:
    long   body;
};

样本中的实际数字并不重要。这把锁效率极高。

您可以在循环中使用InterlockedCompareExchange

    inline void DecrementPendingWorkItems() {
        LONG old_items = this->pendingWorkingItems;
        LONG items;
        while ((items = old_items) > 0) {
            old_items = ::InterlockedCompareExchange(&this->pendingWorkItems,
                                                     items-1, items);
            if (old_items == items) break;
        }
    }

InterlockedCompareExchange函数的作用是:

  if pendingWorkItems matches items, then
    set the value to items-1 and return items
  else return pendingWorkItems

这是以原子方式完成的,也称为比较和交换

使用原子CAS。http://msdn.microsoft.com/en-us/library/windows/desktop/ms683560(v=vs.85).aspx

你可以让它免费上锁,但不能免费等待。

正如Kirill所建议的,这类似于你的情况下的旋转锁。

我认为这正是你所需要的,但我建议在使用之前考虑所有的可能性,因为我根本没有测试过:

inline bool
InterlockedSetIfEqual(volatile LONG* dest, LONG exchange, LONG comperand)
{
    return comperand == ::InterlockedCompareExchange(dest, exchange, comperand);
}
inline bool InterlockedDecrementNotZero(volatile LONG* ptr)
{
    LONG comperand;
    LONG exchange;
    do {
        comperand = *ptr;
        exchange = comperand-1;
        if (comperand <= 0) {
            return false;
        }
    } while (!InterlockedSetIfEqual(ptr,exchange,comperand));
    return true;
}

还有一个问题是,为什么你的待处理工作项应该低于零。你真的应该确保增量的数量与递减的数量相匹配,一切都会好起来的。如果违反了这个约束,我可能会添加一个断言或异常。

相关文章: