【问题标题】:Cause thread release a memory leak?导致线程释放内存泄漏?
【发布时间】:2021-02-25 11:25:54
【问题描述】:

我有一个多线程代码。这是我的代码的一个简单示例:

void SomeClass::ExampleForThread2()
{
  m_thread_ptr = std::make_unique<std::thread>([=]() {
    while (! m_stop)
    {
      try
      {
        // ... do work
      }
      catch (...)
      {
        // ...
      }
    }
#pragma messsage(__DBG__"TODO: not known if release results in a mem leak. Please investigate.")
    //m_thread_ptr.reset(); // now exception will be raised during destruction of std::thread
    m_thread_ptr.release(); // no exception. Will there be a Memory leak for std::thread ?
    });
}

如果 m_stop 为真,while 循环将停止。请问thread2比自动清理吗?在那种情况下,我可以释放并且没有内存泄漏。但这是真的吗?

我现在的答案是:

void SomeClass::ExampleForThread2()
{
if (m_thread_ptr != nullptr)
{
   if (m_thread_ptr->joinable())
   {
      m_tread_ptr->join()
   }  
}
.......

我删除了这部分:

#pragma messsage(__DBG__"TODO: not known if release results in a mem leak. Please investigate.")
    //m_thread_ptr.reset(); // now exception will be raised during destruction of std::thread
    m_thread_ptr.release(); // no exception. Will there be a Memory leak for std::thread ?
    });

该函数是单线程的,不需要锁。

【问题讨论】:

  • std::thread 不是动态分配的,不要使用 std::make_unique 。
  • 你要查看名为join的方法
  • 在 C++20 中你应该使用 std::jthread
  • 谢谢,我按照加入方法的流程进行操作,这对我有帮助。

标签: c++ multithreading memory-leaks


【解决方案1】:

m_thread_ptr.reset 会在线程对象仍可连接时尝试销毁它。这是对std::terminate 的保证调用。
m_thread_ptr.release 是内存泄漏,是的:您从unique_ptr 对象中提取指针,然后将其放在地板上。

只要让函数“用完”,让SomeClass'析构函数清理剩余的线程状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    相关资源
    最近更新 更多