【问题标题】:In C++, can I create a thread and save it as a class member variable so it can be joined automatically in the destructor?在 C++ 中,我可以创建一个线程并将其保存为类成员变量,以便它可以在析构函数中自动加入吗?
【发布时间】:2022-06-10 21:32:07
【问题描述】:

我有一个 c++ 程序,我希望能够在其中调用一个成员函数,该函数将启动一个单独的线程。当我分离线程时,它工作正常,但是我没有办法加入它,所以我想将线程存储为成员变量并在析构函数中自动加入。

我认为这就是下面的代码会做的事情,但是,我得到了下面显示的输出,这让我相信线程永远不会加入。如何使用成员函数加入保存为成员变量的线程?

请指教!

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <windows.h>

using namespace std;

void foo(int i) 
{
    while(true){
        cout << "Foo checkin" << endl;
        Sleep(3000);
    }
}

class ThreadHolder{
    public:
        ThreadHolder(int in){i = in;};
        int i;
        void start_threads(){
            t = thread(foo, i);     // spawn new thread that calls foo()

            std::cout << "foo started\n";
            return;
        }
        ~ThreadHolder();
    private:
        thread t;
};

ThreadHolder::~ThreadHolder(){
    if (t.joinable()){
        cout << "in dest\n";
        t.join();
        cout << "joined\n";
    }
}



int main() 
{
    cout << "in main" << endl;
    ThreadHolder th(1);
    th.start_threads();
    cout << "back in main" << endl;
    return 0;
}

输出:

in main
foo started
back in main
in dest
Foo checkin
Foo checkin
Foo checkin
Foo checkin
Foo checkin
Foo checkin

【问题讨论】:

  • 您需要一些方法来告诉foo 中的循环停止。有很多方法可以做到这一点,所以你必须选择你最喜欢的方式。可以在函数和类之间拆分一个简单的std::atomic&lt;bool&gt; 来告诉循环何时停止。
  • 你希望如何加入一个永不终止的线程?只有终止的线程可以加入,std::thread 是否是类成员不是一个因素。

标签: c++ multithreading


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多