如何终止std::线程

How to terminate a std::thread?

本文关键字:std 线程 终止 何终止      更新时间:2023-10-16

我目前正在开发一个程序,需要从套接字服务器下载一些图像,下载工作将执行很长时间。因此,我创建了一个新的std::thread来实现这一点。

下载后,std::thread将调用当前类的一个成员函数,但这个类很可能已经发布。所以,我有一个例外。

如何解决这个问题?

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;
};

更新

正如@menniumbug所指出的,thread对象不需要动态分配,因为它是可移动的。因此,另一个解决方案如下。

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