Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
parallel_for_each
#include <algorithm> #include <iostream> #include <vector> #include <thread> #include <mutex> template <typename InputIter, typename UnaryFunction> void parallel_for_each(InputIter first, InputIter last, UnaryFunction f) { auto range = std::distance(first, last); size_t approxNumThreads = std::thread::hardware_concurrency(); // number of elements for one thread size_t jobsForThread = range / approxNumThreads; // number of elements for one thread + remainder size_t jobsForMainThread = range % approxNumThreads + jobsForThread; // minus main thread std::vector<std::thread> threads(approxNumThreads - 1); InputIter block_start = first; InputIter block_end = first + jobsForThread; for(size_t i = 0; i < approxNumThreads - 1; ++i) { threads[i] = std::thread(std::for_each<InputIter, UnaryFunction>, block_start, block_end, f); block_start = block_end; block_end += jobsForThread; } std::for_each(block_start, block_start + jobsForMainThread, f); for(auto& t : threads) { if(t.joinable()) { t.join(); } } } int main(int argc, char* argv[]) { std::vector<size_t> vec; for(size_t i = 0; i < 100; ++i) { vec.push_back(i); } parallel_for_each(std::begin(vec), std::end(vec), [&vec](size_t& n) { ++n; }); for(auto e : vec) { std::cout << e << std::endl; } return 0; }
run
|
edit
|
history
|
help
0
Type erasure
BintTree vertical sum
variadic pointer to function template
Newspaper
prime factorization trial division
Fungsi dan for
CharSearch
VecCrossProd
Metodos 2- programa3
C++