C++ 以C+计算资源+;拉伊风格

C++ 以C+计算资源+;拉伊风格,c++,multithreading,c++11,atomic,C++,Multithreading,C++11,Atomic,我希望有一个C++11 RAII组件来计算在多线程环境中存在多少特定类型的资源。我写了以下内容: #include <atomic> #include <iostream> using namespace std; class AtomicCounter { public: AtomicCounter(std::atomic< int > &atomic) : atomic(atomic) { int value = ++t

我希望有一个C++11 RAII组件来计算在多线程环境中存在多少特定类型的资源。我写了以下内容:

#include <atomic>
#include <iostream>

using namespace std;

class AtomicCounter
{
public:
    AtomicCounter(std::atomic< int > &atomic) : atomic(atomic) {
        int value = ++this->atomic;
        cerr << "incremented to " << value << endl;
    }

    ~AtomicCounter() {
        int value = --this->atomic;
        cerr << "decremented to " << value << endl;
    }

private:
    std::atomic< int > &atomic;
};

int main() {
    atomic< int > var;
    var = 0;
    AtomicCounter a1(var);
    {
    AtomicCounter a2(var);
    cerr << "Hello!" << endl;
    AtomicCounter a3(var);
    }
    cerr << "Good bye!" << endl;
    return 0;
}
#包括
#包括
使用名称空间std;
类原子计数器
{
公众:
原子计数器(std::atomic&atomic):原子(atomic){
int value=++this->atomic;

cerr我看到的主要问题,特别是对于多线程用例,是您的
原子
可能超出范围,留下一个悬而未决的引用。也许共享指针是一种替代方法。我觉得这没有多大意义。如果您想获得大量可用资源,通常需要访问这些资源在这种情况下,您经常希望将项目放入一个集合中,以便可以找到它们(在这种情况下,集合的大小会告诉您有多少可用)@mindriot在我的例子中,我可以假设原子保留在范围内。但是,很高兴了解更一般的情况。@JerryCoffin我主要需要知道周围是否有这些资源,以便我知道何时执行某些清理操作。除此之外,这些资源(线程)独立工作。使用集合需要锁定,而我的实现不需要(如果
原子
是无锁的,就像我认为在大多数实现中一样)。我一直在寻找这一点。它正是我所需要的——一种多线程环境中的RAII计数方式