原子比较,如果更少,则有条件地减去

atomic compare and conditionally subtract if less

本文关键字:有条件 比较 如果      更新时间:2023-10-16

我管理一些并发线程使用的内存,我有一个变量

unsigned int freeBytes

当我从任务请求一些内存时

无符号整数字节需要

我必须检查是否

需要的字节数<=免费字节数

如果是,请保留 freeBytes 的旧值,并从 freeBytes bytesNeed 中原子地减去。

原子库或x86是否提供这种可能性?

使用原子比较和交换操作。在伪代码中:

do {
    unsigned int n = load(freeBytes);
    if (n < bytesNeeded) { return NOT_ENOUGH_MEMORY; }
    unsigned int new_n = n - bytesNeeded;
} while (!compare_and_swap(&freeBytes, n, new_n));

使用实际C++ <atomic>变量,实际变量可能看起来非常相似:

#include <atomic>
// Global counter for the amount of available bytes
std::atomic<unsigned int> freeBytes;    // global
// attempt to decrement the counter by bytesNeeded; returns whether
// decrementing succeeded.
bool allocate(unsigned int bytesNeeded)
{
    for (unsigned int n = freeBytes.load(); ; )
    {
        if (n < bytesNeeded) { return false; }
        unsigned int new_n = n - bytesNeeded;
        if (freeBytes.compare_exchange_weak(n, new_n)) { return true; }
    }
}

(请注意,最终compare_exchange_weak通过引用获取第一个参数,并在交换失败时用原子变量的当前值更新它。

相比之下,递增值("解除分配?可以通过简单的原子添加来完成(除非您要检查溢出(。这在某种程度上是无锁容器的症状:创建某些东西相对容易,假设资源无限,但删除需要循环尝试。