原子比较,如果更少,则有条件地减去
atomic compare and conditionally subtract if less
我管理一些并发线程使用的内存,我有一个变量
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
通过引用获取第一个参数,并在交换失败时用原子变量的当前值更新它。
相比之下,递增值("解除分配?可以通过简单的原子添加来完成(除非您要检查溢出(。这在某种程度上是无锁容器的症状:创建某些东西相对容易,假设资源无限,但删除需要循环尝试。
相关文章:
- 如何使用 soong 命名空间来有条件地编译模块
- 用户定义的结构是否有默认C++比较器?
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 根据模板类型有条件地删除变量
- 有条件地选择带有 decltype() 和三元运算符的类型
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 有条件的打印和计数在 std::map 上有限制
- 如何在 c++ 中有条件地包含标头?
- 如何仅在Qt是用ltcg构建时才有条件地启用ltcg?
- 如何在Visual Studio 2019中有条件地编译c++源文件
- C++可以有条件地向下转换类指针吗
- 使用 SFINAE 有条件地解析分配器成员
- 有条件地删除宏
- 有条件地包含C++标准库
- 如何有条件地将元素添加到 std::array - C++11
- 是否根据编译器版本有条件地包含源文件
- 有条件地启用类C++构造函数
- 我可以有条件地使用多个参数吗?
- 有条件比较的优雅解决方案
- 原子比较,如果更少,则有条件地减去