首页 > 解决方案 > C++ 在单独的线程中调用类方法

问题描述

比如说,我有一个有两种方法的类:一个主线程和一个单独的线程。

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

using namespace std;

class Foo
{
    bool is_ready;
public:
    Foo()
    {
        is_ready = false;
    }

    void async_func()
    {
        this_thread::sleep_for(chrono::milliseconds(2000));  // do some long stuff
        is_ready = true;
    }

    void main_thread_func()
    {
        thread t([&] (Foo* foo) { foo->async_func(); }, this);
        t.join();
        
        while(true)
        {
            cout << is_ready << endl;
            this_thread::sleep_for(chrono::milliseconds(100));
        }
    }
};

int main()
{
    Foo foo;
    foo.main_thread_func();
    return 0;
}

我想查看一条状态为“is_ready”的消息,以了解另一个线程函数的进度。实际上,只有当它变为“真实”时,我才能看到消息。

函数停止时如何查看所有未等待的进度?

标签: c++multithreading

解决方案


您之前调用了 join 函数,因此主线程正在等待完成创建的线程。你应该在正确的地方调用 join 函数,例如在 while(true) 之后。


推荐阅读