Emplace back thread on vector

拥有回忆 提交于 2021-02-07 18:01:55

问题


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?


回答1:


What is happening in your code that you are constructing a three default threads then adding other 3 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 spwan:

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);


来源:https://stackoverflow.com/questions/39266461/emplace-back-thread-on-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!