我目前正在开发一个程序,需要从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/