[英]How to terminate a std::thread?
我当前正在开发一个程序,该程序需要从套接字服务器下载一些图像,并且下载工作将执行很长时间。 因此,我创建了一个新的std::thread
来执行此操作。
一旦下载, std::thread
将调用当前Class的成员函数,但是该Class可能已经发布。 所以,我有一个例外。
如何解决这个问题呢?
void xxx::fun1()
{
...
}
void xxx::downloadImg()
{
...a long time
if(downloadComplete)
{
this->fun1();
}
}
void xxx::mainProcees()
{
std::thread* th = new thread(mem_fn(&xxx::downloadImg),this);
th->detach();
//if I use th->join(),the UI will be obstructed
}
不要拆线。 取而代之的是,您可以拥有一个数据成员,该成员持有一个指向thread
的指针,并将该线程join
到析构函数中。
class YourClass {
public:
~YourClass() {
if (_thread != nullptr) {
_thread->join();
delete _thread;
}
}
void mainProcees() {
_thread = new thread(&YourClass::downloadImg,this);
}
private:
thread *_thread = nullptr;
};
更新
就像@milleniumbug指出的那样,您不需要动态分配thread
对象,因为它是可移动的。 因此,另一个解决方案如下。
class YourClass {
public:
~YourClass() {
if (_thread.joinable())
_thread.join();
}
void mainProcess() {
_thread = std::thread(&YourClass::downloadImg, this);
}
private:
std::thread _thread;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.