如何终止std :: thread?

tob*_*bin 5 c++ multithreading cocos2d-x c++11 stdthread

我目前正在开发一个程序,需要从套接字服务器下载一些图像,下载工作将执行很长时间.所以,我创造了一个新std::thread的做法.

一旦下载,std::thread它将调用当前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
}
Run Code Online (Sandbox Code Playgroud)

for*_*ack 5

不要拆线。取而代之的是,您可以具有一个数据成员,该成员持有指向的指针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;
};
Run Code Online (Sandbox Code Playgroud)

更新

就像@milleniumbug指出的那样,您不需要为thread对象动态分配,因为它是可移动的。因此,另一个解决方案如下。

class YourClass {
public:
    ~YourClass() {
        if (_thread.joinable())
            _thread.join();
    }
    void mainProcess() {
        _thread = std::thread(&YourClass::downloadImg, this);
    }
private:
    std::thread _thread;
};
Run Code Online (Sandbox Code Playgroud)