问题
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