So I need a thread pool for my application, which led me to create a std::map<int, std::thread> object.
I've encountered some very unexpected behavior, which can be simplified to this:
std::map<int, std::thread> threads;
threads.insert(std::pair<int, std::thread>(1, std::thread([]() {
        std::cout << "I'm the first thread and I'm gonna work\n";
    })));
threads[1].join();
std::cout << "Thread 1 joinable? " << threads[1].joinable() << "\n";
threads.insert(std::pair<int, std::thread>(1, std::thread([]() {
        std::cout << "I'm not gonna work at all\n";
    })));
threads[1].join();
The output is
I'm the first thread and I'm gonna work
Thread 1 joinable? 0
Right after, std::terminate() is called and program receives SIGABRT signal.
Live debugging suggested that terminate is being called because joinable() is true, but I just checked and figured it's not!
Moreover, the way to overcome it was simply to add the following line after join()ing:
threads.erase(1);
That leaves me a bit confused, as it looks like a new instance of std::thread was created just before my insert call... Can someone hint me about this unexpected behavior?