Skip to content

Instantly share code, notes, and snippets.

@stmtk1
Created December 24, 2019 03:17
Show Gist options
  • Save stmtk1/70c3406db52fd33ce27095c05cf8243e to your computer and use it in GitHub Desktop.
Save stmtk1/70c3406db52fd33ce27095c05cf8243e to your computer and use it in GitHub Desktop.
template<typename T>
std::vector<T> thread_map(int thread_num, std::vector<T> origin_arg, std::function<T(T)> func) {
std::vector<std::thread> threads_;
std::vector<T> output_(origin_arg.size());
for(int i = 0; i < thread_num; ++i){
auto runner = [i, func, origin_arg, thread_num, &output_]() {
int array_size = origin_arg.size();
int start = (array_size + thread_num - 1) / thread_num * i;
int end = std::min((array_size + thread_num - 1) / thread_num * (i + 1), array_size);
for(int j = start; j < end; ++j) {
output_[j] = func(origin_arg[j]);
}
};
threads_.emplace_back(std::thread(runner));
}
for(int i = 0; i < thread_num; ++i) {
threads_[i].join();
}
return output_;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment