【发布时间】:2016-06-05 20:01:18
【问题描述】:
我想创建一个 C++ 类,其中一个线程每分钟做一次工作。
首先,我可以将线程定义为变量成员吗?
class my_class
{
public:
my_class()
: my_thread_(task, this)
{
}
~my_class()
{
done_ = true;
}
void run()
{
while(!done_)
{
...do work in the thread...
}
}
private:
static task(my_class * ptr)
{
ptr->run();
}
std::thread my_thread_;
std::atomic<bool> done_ = false;
};
其次,我可以使用带有线程的智能指针吗?
class my_class
{
public:
~my_class()
{
done_ = true;
}
void init()
{
my_thread_.reset(new std::thread(task, this));
}
void run()
{
while(!done_)
{
...do work in the thread...
}
}
private:
static task(my_class * ptr)
{
ptr->run();
}
std::unique_ptr<std::thread> my_thread_;
std::atomic<bool> done_ = false;
};
在我看来,我需要在子线程被销毁之前加入它,但我想知道 std::thread 的析构函数是否知道安全地这样做。
【问题讨论】:
标签: c++ multithreading c++14