我当前正在开发一个程序,该程序需要从套接字服务器下载一些图像,并且下载工作将执行很长时间。因此,我创建了一个新的std::thread
来做到这一点。
一旦下载,std::thread
将调用当前Class的成员函数,但是该Class可能已经发布。所以,我有一个异常(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
}
最佳答案
不要拆线。取而代之的是,您可以具有一个数据成员,该成员持有指向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;
};
关于c++ - 如何终止std::thread?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38538438/