【发布时间】:2017-08-04 10:50:53
【问题描述】:
我一直在寻找一种方法来保护整数以原子方式递增但使用绑定检查。 我四处寻找其他帖子,但似乎没有一个好的解决方案(有些是 C++11 之前的版本)。
我需要一个类似如下的库:
class bounded_atomic_uint
{
private:
uint32_t ctr;
uint32_t max;
mutex mtx;
public:
bounded_atomic_uint(uint32_t max = UINT32_MAX) : ctr(0), max(max) {}
~bounded_atomic_uint() = default;
// make in uncopyable and un-movable
bounded_atomic_uint(bounded_atomic_uint&&) = delete;
bounded_atomic_uint& operator=(bounded_atomic_uint&&) = delete;
bool inc();
bool dec();
uint32_t get();
};
bool bounded_atomic_uint::inc() {
lock_guard<mutex> lck (mtx);
if (ctr < max) {
ctr++;
return true;
}
else
{
cout << "max reached (" << max << ")" << endl; // to be removed!
return false; // reached max value
}
}
bool bounded_atomic_uint::dec() {
lock_guard<mutex> lck (mtx);
if (ctr > 0) {
ctr--;
return true;
}
else {
cout << "min reached (0)" << endl; // to be removed!
return false; // reached min value
}
}
uint32_t bounded_atomic_uint::get() {
lock_guard<mutex> lck (mtx);
return ctr;
}
使用如下:
#include <iostream>
#include <mutex>
#include <cstdint>
using namespace std;
int main() {
bounded_atomic_uint val(3);
if (val.dec())
cout << "error: dec from 0 succeeded !!" << endl;
cout << val.get() << endl; // make sure it prints 0
val.inc();
val.inc();
cout << val.get() << endl;
if (!val.inc())
cout << "error: havent reached max but failed!!" << endl;
if (val.inc())
cout << "error max not detected!!" << endl;
cout << val.get() << endl;
return 0;
}
有没有更简单(或更正确)的方法? std::atomic 和 boost::atomic 似乎都没有办法避免越界检查(在锁内)。
如果不是,这个 simplistic 类是否足够好? 还是我在这里遗漏了什么?
注意库上的 couts 在实际使用时将被删除!
【问题讨论】:
-
仅供参考,您正在寻找的术语是“饱和算术”。
标签: c++ multithreading c++11 atomic