如何终止std::线程
How to terminate a std::thread?
我目前正在开发一个程序,需要从套接字服务器下载一些图像,下载工作将执行很长时间。因此,我创建了一个新的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;
};
相关文章:
- 即发即弃 std::线程对象清理自身
- std::线程导致程序中止
- 在std::线程中使用已分配的结构数据
- 使用-static libstdc++时std::线程弱,因此在运行时会导致崩溃
- std::线程与 pthread_setschedparam 与 C++ 11.
- 运行 std::线程不在构造函数中
- C++ std::线程调用方法,从对象原因到调用此类的析构函数
- 编译问题 C++ 同时,尝试通过调用另一个对象中的成员函数来创建 std:: 线程
- 错误:静态断言失败:std ::线程参数必须在转换为rvalues后不可行
- C STD ::线程中的种族状况或内存损坏
- 在 Valgrind 输出中仍然可以访问 std 线程向量的块
- 将类Cotaining std ::线程添加到向量
- 如何使用mingw编译C STD ::线程代码
- 从其他std ::线程更新QT GUI
- STD ::线程不会退出
- 处理 std::线程包装器类的立即销毁
- C++ std 线程并列出分段错误(核心转储)
- 杀死后的STD ::线程如何处理
- 干净取消在输入/输出调用中被阻止的 std::线程
- std ::线程最大并发线程