c++ - 线程作为成员变量

标签 c++ multithreading

我想将一个线程保存为类的成员变量。我想在“开始”方法中启动线程,并在“停止”方法中停止线程。我还想确保线程加入,无论是否调用“停止”方法。

我设计了以下代码,使用 shared_ptr 和用于加入线程和删除线程指针的自定义删除器,但我不能 100% 确定它是否完全正确。

请对此发表评论。这里一切都好吗?或者也许有更好的方法来做到这一点(例如使用 unique_ptr 或设计其他 RAII 类)?

#include <thread>
#include <iostream>
#include <memory>
using namespace std::chrono_literals;

void fun() { std::cout << "inside thread\n"; std::this_thread::sleep_for(1s); }

class A
{
public:
    A() : pT(nullptr) {}

    void start()
    {
        std::cout << "starting...\n";
        pT.reset(new std::thread(fun), [](auto p) {
            if (p->joinable()) 
            { 
                std::cout << "joining thread\n";
                p->join(); 
            }
            std::cout << "deleting thread\n"; 
            delete p;
       });
    }

    void stop()
    {
        std::cout << "stopping...\n";
        pT.reset();
    }

private:
    std::shared_ptr<std::thread> pT;
};
int main()
{
    A a;
    a.start();
    std::this_thread::sleep_for(2s);
    a.stop();

    return 0;
}

输出是正确的:

starting...
inside thread
stopping...
joining thread
deleting thread

最佳答案

在我的例子中,我喜欢控制创建什么以及何时销毁它。所以,我的建议是:

您可以将线程指针添加为您的类的成员,并检查它是否已完成,正如我在本例中向您展示的那样:

class A{

   std::thread *pThread = nullptr; \\ Thread Pointer
   //...
public:
   A();
   ~A();
   void start();
   void stop();
}

并将其用作:

void start()
{
    if(pThread == nullptr) 
    {
       pThread = new thread(fun); //Create the thread and store its reference
    }
}

~A()
{
    if (pThread != nullptr)
    {
        if(pThread->joinable()) \\Wait until the thread has been finished
            pThread->join();
        delete pThread; \\IMPORTANT, release the memory. 
    }
}

在这个例子中,我使用线程来同步销毁类,直到线程完成才会销毁。

注意:如果你想使用某个类的方法作为运行线程的函数,你可以使用std::bind

Also you can use smart pointer as unique_ptr instead of std::thread, as i made in this sample. In this case the memory will be release when the class get to be destroyed, so be sure the thread is finished before delete this pointer o leave the context (Class).

关于c++ - 线程作为成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45602004/

相关文章:

c++ - 使用 IEEE 754 浮点 double 据类型安全往返整数值

c++ - CLion 中的 CMake,调用远程构建而不是本地构建

ios - 难以捉摸的崩溃 : terminated due to memory issue

c++ - OpenMP #pragma,只有一个线程在处理我的代码

c++ - 用于 c++11 线程的 RW 锁

C++ 使 char 数组在输入时识别空格

c++ - 跟踪程序函数调用

c# - Swig:将 std::vector<unsigned char> 传递给从 c++ 生成的 c# 函数

vb.net - VB.NET 中从另一个线程挂起一个线程

android - WebViewCore 内部线程中 StatFs 中的 IllegalArgumentException