原子比较,如果小于则有条件地减去

use*_*779 3 c++ x86 atomic stdatomic

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

无符号整数 freeBytes

当我从任务中请求一些记忆时

无符号整数字节需要

我必须检查是否

bytesNeeded<=freeBytes

如果是,则保留 freeBytes 的旧值并从 freeBytes bytesNeeded 中自动减去。

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

Ker*_* SB 5

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

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));
Run Code Online (Sandbox Code Playgroud)

使用真正的 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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

(请注意,finalcompare_exchange_weak通过引用获取第一个参数,并在交换失败的情况下使用原子变量的当前值更新它。)

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