Remove thread from vector upon thread completion

Viewed 3892

I have a vector of threads in my C++ program.

std::vector<std::thread> threadList;

I then create a thread and push it into the vector.

threadList.push_back(std::thread([]() { ... }));

How can I remove the thread from the threadList vector when the lambda function finishes execution?


Edit

I've come up with somewhat of a solution; Before the thread lambda function returns, it iterates through the vector to find a match in ID with this_thread::get_id().

Through Visual Studio debugging line by line, I see that it finds a match in ID and the erase function is executed, but as soon as threadList.erase(threadList.begin() + index); is executed, I come accross an unhandled exception at the thread's deconstructor function.

I've written a small piece of code which replicates this error.

vector<thread> threadList;

threadList.push_back(thread([]() {
    Sleep(1000);
    threadList.erase(threadList.begin());
}));

Sleep(2000);

//for_each(threadList.begin(), threadList.end(), mem_fn(&thread::detach));
//threadList.clear();

This code results in the screenshot below.

enter image description here

2 Answers
Related