c++ - 线程基类 C++

标签 c++ multithreading c++11 pthreads

我想做一些线程基类。我编写了代码,我认为它应该可以工作,它编译并运行但它什么都不显示。我认为,问题出在回调中,但我可能是错的。那么,我的代码有什么问题?

class ThreadedBase
{
public:
    ThreadedBase(bool start = false) : m_running(false) {
        if (start)
            this->start();
    }
    virtual ~ThreadedBase() {
        m_running = false;
        m_thread.join();
    }

    bool start(){
        if (m_running) {
            return false;
        };
        m_thread = std::thread(&ThreadedBase::run, this);
        m_running = true;
        return true;
    };

    bool stop(){
        if (!m_running) {
            return false;
        };
        m_running = false;
        return true;
    };

protected:
    virtual void threadedBlock() = 0;

    void run() {
        while (m_running) {
            threadedBlock();
        }
    }

private:
    std::thread m_thread;
    bool m_running;
};

class Test : public ThreadedBase
{
public:
    Test(bool start = true) : ThreadedBase(start) {}

    void threadedBlock() {
        std::cout << "Task\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
};

int main()
{
    Test t(true);
    t.start();

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

    return 0;
}

最佳答案

你需要添加:

m_running = true;

之前:

m_thread = std::thread(&ThreadedBase::run, this);

关于c++ - 线程基类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054186/

相关文章:

C++ Winapi 在 .exe 文件中包含 DLL

c++ - C++库的C部分是否自动为C99?

c++ - std::move、std::forward、值类型和模板推导

.net - 基于程序描述的多线程推荐

c++ - 模板类的工厂方法

c++ - std::thread - 命名你的线程

使用 Guava FutureCallback 接口(interface)进行 Java 多线程编程

Java 等待通知,两个线程作为同一个类

c++ - constexpr 连接两个或多个 char 字符串

c++ - 读取(int fd,void *buf,size_t count): prevent implicit conversion