jeudi 1 septembre 2016

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?

Aucun commentaire:

Enregistrer un commentaire