'Emplace back thread on vector

Why this cause undefined behavior?

#include <iostream>
#include <thread>
#include <vector>

std::vector<std::thread> threads(3);

void task() { std::cout<<"Alive\n";}
void spawn() {
        for(int i=0; i<threads.size(); ++i)
                //threads[i] = std::thread(task);
                threads.emplace_back(std::thread(task));

        for(int i=0; i<threads.size(); ++i)
                threads[i].join();
}

int main() {
        spawn();
}

If I will create threads as in commented line thread is copied/moved assignment so its fine, but why is not working when creating thread in place?



Solution 1:[1]

What is happening in your code is that you construct three default threads, then add three further threads.

Change:

std::vector<std::thread> threads(3);

To:

std::vector<std::thread> threads;
const size_t number_of_threads = 3;

int main() {
    threads.reserve(number_of_threads);
    spawn();
}

And inside spawn:

void spawn() {
    for (int i = 0; i < number_of_threads; ++i) {
        threads.emplace_back(std::thread(task));
    }
    for (int i = 0; i < threads.size(); ++i) {
        threads[i].join();
    }
}

When you are using emplace_back or push_back, you must not allocate the memory before, because that will call the constructor of threads. You should just reserve it.

BTW, since you are using emplace_back not push_back you can directly write:

threads.emplace_back(task);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neonit