【发布时间】: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