user2458798
user2458798

Reputation: 11

std::async: The created threads still alive even though the tasks are finished?

I'm currently using std::async in order to launch a several tasks(4) simultaneously, after the launch I wait for the task to finish using std::future objects.The problem is that when I see the system monitoring, it appears that more than 13 threads have been created and do not terminate.

Here is the piece of code:

System system;
std::vector<Compressor> m_compressorContainer(4);
std::vector<future<void> > m_futures(4);

while( system.isRunning() )
{

int index=0;

//launch one thread per compressor
for ( auto &compressor : m_compressorContainer )
{   
  m_futures[index++] = std::async(std::launch::any, &Compressor::process, compressor );
}

//wait for results
std::for_each( m_futures.begin(),m_futures.end(), [](std::future<void> &future){ future.get(); } );

}

Since I'm waiting the end of each thread, I was expecting that the number of thread will always be 4 and not 13.

No idea ?

Upvotes: 1

Views: 619

Answers (1)

MSalters
MSalters

Reputation: 179991

Threads, like memory, may be kept alive by the library for reuse in the future. E.g. delete p; isn't guaranteed to return memory to the system either.

Upvotes: 2

Related Questions