c++ - 在 C++ 中,在单态类/静态成员的析构函数中管理资源是个坏主意吗?

标签 c++ multithreading c++11 stdthread monostate

我正在尝试实现管理某些 std::thread 的 monostate 类。线程一直运行直到标志变为等于 false。标志更改为 false 后 - 线程停止。但看起来我必须明确地调用停止方法。在析构函数中调用它会给我带来运行时错误(在 GCC 4.8 for ARM、GCC 4.9 for x86_64 和 MSVC 2017 上测试)。 这种行为是由于

"Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program."

所以析构函数调用被省略了?

代码示例:

#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>


void runThread(const std::atomic<bool> &_isRunning) {

    while (_isRunning) {

        std::cout << "Me running.." << std::endl;

        std::this_thread::sleep_for(std::chrono::milliseconds(30));

    }

}

class test {

    static std::thread          thread;
    static std::atomic<bool>    isRunning;


public:

    test();
    ~test();

    static void go();
    static void stop();


};

std::thread         test::thread;
std::atomic<bool>   test::isRunning{ false };


test::test() {}

void test::go() {

    isRunning = true;
    thread = std::thread(runThread, std::ref(isRunning));

}

void test::stop() {

    isRunning = false;

    if (thread.joinable()) {

        thread.join();

    }

}

test::~test() {

    stop();

}


int main() {

    test::go();

    std::this_thread::sleep_for(std::chrono::seconds(5));

    std::cout << "Done here!!!!!!!!!!!!!!!!!";

    // Will not crash anymore if uncomment
    //test::stop();

    return 0;

}

将 std::async 与 std::feature 一起使用会得到相同的结果但没有错误。线程一直在运行。

附言


使类成为非单态类可以解决运行时错误,但给我留下了这个问题。管理资源对于单态类/静态成员来说是一种不好的做法吗?

最佳答案

 ~test();

应该在销毁任何“测试”对象之前调用。您没有在代码中创建“测试”对象,所以您是对的,

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.

关于c++ - 在 C++ 中,在单态类/静态成员的析构函数中管理资源是个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339276/

相关文章:

c++ - 使用 and 运算符进行微优化

c++ - 为什么 std::map (以及 STL 中的其他关联容器)上没有 front() 方法?

java - 出于可扩展性目的,不使用 ConcurrentHashMap 并发访问 Java Map

c++ - constexpr 函数是隐式静态的吗?

c++ - 为什么可以使用 [=] 来修改 lambda 中的成员变量?

c++ - 返回 STL 列表作为参数

c++ - 在 C++ 中重载 **

python asyncio REST api 调用给出错误

android - 线程,UI线程,工作线程,异步任务

c++ - 为什么 gcc 4.9 (trunk) 这么慢?