lundi 4 mars 2019

C++ stack leak with std::thread class

I have what appears to be a stack leak directly attributable to using std::thread. To boil it down to the simplest example, I used the example code from https://en.cppreference.com/w/cpp/thread/thread/detach but modified it to loop and call the thread creating function multiple times and removed extraneous code:

#include <chrono>
#include <thread>

void independentThread() 
{
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

void threadCaller() 
{
    std::thread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

int main() 
{
    for(int i=0; i < 100; i++)
       threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(50));
}

Then I compiled the code with g++ 8.3:

 g++ -std=c++14 -pthread -g -fstack-check -fstack-protector-all -finstrument-functions thread_test.cpp -o t_test

Then I ran the code with valgrind:

valgrind --tool=massif --stacks=yes --time-unit=ms ./t_test

The output from valgrind is run through "ms_print" and then moved to excel to chart: Chart of stack and heap bytes

Everything I see points to a memory leak caused by the thread. I've tried using join but even then there is still a leak and join won't work for my application. I'm running this on linux 4.14.77-70.59.amzn1.x86_64 with gcc version 8.3.0

Is there something I should be doing differently with the thread or is this "leak" just a misreported memory loss by valgrind?

Thanks

Aucun commentaire:

Enregistrer un commentaire