简体   繁体   English

C++ 在单独的线程中调用 class 方法

[英]C++ Call a class method in a separate thread

Say, I have a class with two methods: a main thread and a separate one.说,我有一个 class 有两种方法:一个主线程和一个单独的方法。

#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;
}

I want to see a message with the "is_ready" state to learn the progress of another thread's function.我想看一条带有“is_ready”的消息 state 来了解另一个线程的 function 的进度。 Actually, I can see messages only when it make "true".实际上,只有当它变为“真实”时,我才能看到消息。

How to see all the progress not waiting when the function stops?当 function 停止时,如何查看所有未等待的进度?

You call the join function before while so main thread is waiting to finished the created thread.您之前调用了join function,而主线程正在等待完成创建的线程。 You should call join function in right place for example after while(true).您应该在正确的位置调用 join function 例如在 while(true) 之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM