我想将一个线程保存为类的成员变量。我想在“开始”方法中启动线程,并在“停止”方法中停止线程。我还想确保线程加入,无论是否调用“停止”方法。
我设计了以下代码,使用 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 ofstd::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/