如何终止一个std::thread?

How to terminate a std::thread?

我目前正在开发一个程序,需要从socket服务器下载一些图片,下载工作会执行很长时间。所以,我创建了一个新的 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;
};