Emplace在传染媒介的后面螺纹

Mat*_*zak 2 c++ vector c++11

为什么会导致未定义的行为?

#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();
}
Run Code Online (Sandbox Code Playgroud)

如果我将创建线程,如在注释行中线程被复制/移动赋值所以它很好,但为什么在创建线程时不起作用?

Hum*_*awi 5

在您的代码中发生了什么,您正在构建三个默认线程,然后添加其他3个线程.

更改:

std::vector<std::thread> threads(3);
Run Code Online (Sandbox Code Playgroud)

至:

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

int main(){
    threads.reserve(number_of_threads);
    spawn();
}
Run Code Online (Sandbox Code Playgroud)

内部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();
    }
}
Run Code Online (Sandbox Code Playgroud)

当您使用emplace_back或时psuh_back,您不得以前分配内存.你应该reserve这样做.

顺便说一句,因为你使用的emplace_back不是push_back你可以直接写:

threads.emplace_back(task);
Run Code Online (Sandbox Code Playgroud)