c++ - 如何终止 std::thread?

标签 c++ multithreading c++11 cocos2d-x stdthread

我目前正在开发一个程序,需要从socket服务器下载一些图片,下载工作会执行很长时间。因此,我创建了一个新的 std::thread 来执行此操作。

下载完成后,std::thread 会调用当前类的一个成员函数,但这个类很可能已经被释放了。所以,我得到了一个异常(exception)。

如何解决这个问题?

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
}

最佳答案

不要分离线程。相反,您可以拥有一个数据成员,该成员包含指向 线程 的指针,并在析构函数中加入线程。

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

关于c++ - 如何终止 std::thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38538438/

相关文章:

c++ - SDL2 无法正确绘制矩形

c++ - 凭证提供者。显示一种进度条并禁用密码或 PIN 字段

c++ - 使用 128 位种子的伪随机排列

c++ - 为什么十进制浮点运算的提议没有被 C++0x 接受?

c++11 - 为什么 ThreadSanitizer 会报告这个无锁示例的竞争?

c++ - Wind River Workbench 3.3 中具有数据类型的枚举

c++ - 并行化 SVD 计算 c++

multithreading - 一个应用程序中有多少个并发线程是很多?

java - 下载数据时 UI-Thread 似乎滞后

c++ - 为什么win32线程不自动退出?