调用加入后删除std :: thread吗?

硼氧磷

我有一些代码可以std::thread从C ++ 11<thread>标头动态分配新的代码,如下所示:

std::thread *th = new thread( /* my args */);

一段时间后,我打电话给join:

th->join();

由于我是动态分配线程的,因此是否还需要调用delete th;以释放内存?如果可以,我还需join()要先打电话吗?

EyasSH

为避免内存泄漏,您需要同时执行以下操作:join运行线程,并确保销毁/删除了线程(让它超出堆栈分配范围,std::threads或显式调用delete std::thread*)。

参见cppreference中的thread ::〜thread:

在以下情况下,线程对象没有关联的线程(并且可以安全地销毁):

  • 它是默认构造的
  • 它从
  • join()已被调用
  • detach()已被调用

因此,无法安全地销毁未连接的线程。

join()std::thread仍然会占据一些内存。因此,如果它在堆上,则需要确保已正确释放它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

可以从非父线程调用std :: thread :: join()吗?

C ++ 11:如何在执行函数退出后立即加入std :: thread?

分离的std :: thread终止后是否需要删除?

在调用clear时,thread_local std :: list是否放弃分配的内存吗?

std :: this_thread :: sleep_for()可以虚假唤醒吗?

std :: thread的共享指针是一种不好的做法吗?

在std :: thread中joinable()然后join()是线程安全的吗?

设置* interrupt status *调用Thread.sleep()吗?

调用Thread.start()时发生在传递之前吗?

这是调用Thread.Abort()的合适地方吗?

std :: future :: get()或std :: future :: wait()替代std :: thread :: join()吗?

使用删除的函数'std :: thread :: thread(const std :: thread&)'

为什么当我没有调用release()时,std :: make_unique <std :: thread>(somefun())会生成崩溃,调用时会崩溃吗?

std :: thread调用类方法

错误:静态断言失败:转换为右值后,std :: thread参数必须可调用

std::thread 参数在转换为右值后必须是可调用的

By-ref参数:这是std :: thread和std :: bind之间的不一致吗?

可以使用boost :: threads中的std :: this_thread *函数吗?

std :: thread构造函数传递指针和ref传递之间有区别吗?

std :: this_thread :: yield与linux上的sched_yield有什么不同吗?

将分配std :: thread对象从同一线程移走可以吗

使用ctor参数将函子传递到std :: thread。可能吗?

默认构造函数std :: thread :: id不应该创建一个“ NULL” id吗?

我可以将每个动作引用的数组传递给std :: thread吗?

std::thread 构造函数完成实际上与执行线程的开始同步吗?

std :: thread(c ++ 11)中使用的函数可以有[[noreturn]]吗?

调用线程会在thread.join()之后看到对局部变量的修改吗?

在调用事件时使用Thread.Sleep,但不起作用吗?(C#)

删除DOM元素后,我应该调用jQuery.off吗?