在我的一个应用程序中,当我开始使用 std::async 时,我引入了内存泄漏。在使用 Dr. memory 工具检查问题后,我发现 std::async 经常泄漏内存。
我做了一个重现问题的快速测试:
#include <Windows.h>
#include <algorithm>
#include <future>
using namespace std;
void testMethod()
{
for (int i = 0; i < 4; i++)
Sleep(10);
}
int main()
{
for (int i = 0; i < 100; i++)
{
auto result = async(launch::async, testMethod);
result.wait();
}
return 1;
}
上面的代码怎么可能在 Windows 上泄漏内存?Linux 上不会出现该问题。Dr. memory 会产生以下日志:
Error #1: REACHABLE LEAK 40 direct bytes 0x007badb8-0x007bade0 + 0 indirect bytes
# 0 replace_operator_new_nomatch [d:\drmemory_package\common\alloc_replace.c:2732]
# 1 MSVCR120D.dll!Concurrency::details::SubAllocator::Alloc [f:\dd\vctools\crt\crtw32\concrt\suballocator.cpp:201]
# 2 MSVCR120D.dll!Concurrency::details::ExternalContextBase::Alloc [f:\dd\vctools\crt\crtw32\concrt\externalcontextbase.cpp:238]
# 3 MSVCR120D.dll!Concurrency::Alloc [f:\dd\vctools\crt\crtw32\concrt\suballocator.cpp:34]
# 4 Concurrency::details::_AllocBase::operator new [c:\program files (x86)\microsoft visual studio 12.0\vc\include\concrt.h:298]
# 5 Concurrency::task<>::_TaskInitWithFunctor<> [c:\program files (x86)\microsoft visual studio 12.0\vc\include\ppltasks.h:3982]
# 6 Concurrency::task<>::_TaskInitMaybeFunctor<> [c:\program files (x86)\microsoft visual studio 12.0\vc\include\ppltasks.h:4551]
# 7 Concurrency::task<>::task<><> [c:\program files (x86)\microsoft visual studio 12.0\vc\include\ppltasks.h:4198]
# 8 Concurrency::create_task<> [c:\program files (x86)\microsoft visual studio 12.0\vc\include\ppltasks.h:4673]
# 9 std::_Task_async_state<>::_Task_async_state<><> [c:\program files (x86)\microsoft visual studio 12.0\vc\include\future:906]
#10 std::_Get_associated_state<> [c:\program files (x86)\microsoft visual studio 12.0\vc\include\future:1859]
#11 std::_Async<>