In a tutorial I am following, the author wrote a program that showed that the destructors of std::future
s don't always execute the task. In the following program, 10 threads created with std::async()
are moved into the vector, and then we wait for their destructors to run.
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int main()
{
std::cout << "Main thread id: " << std::this_thread::get_id() << std::endl;
std::vector<std::future<void>> futures;
for (int i = 0; i < 10; ++i)
{
auto fut = std::async([i]
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << std::this_thread::get_id() << " ";
});
futures.push_back(std::move(fut));
}
}
The result is machine-dependent, but what we found was that only 6 threads were launched when the destructors ran (we only got 6 ids printed after the main thread id output). This meant that the other four were deferred, and deferred threads don't run during std::future
's destructors.
My question is why were some threads forced to execute while others were deferred. What is the point of deferring them if the life of the std::future
is ending?