fork(1) download
  1. #include <iostream>
  2. #include <thread>
  3. #include <functional>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7. inline void ParallelFor( const size_t startIdx, const size_t endIdx, std::function< void( size_t ) >&& fn, const size_t numThreads = std::thread::hardware_concurrency() )
  8. {
  9. const size_t portion = std::max( 1u, (endIdx - startIdx) / numThreads );
  10. std::vector< std::thread > threads;
  11. for ( size_t i = startIdx; i < endIdx; i += portion )
  12. {
  13. int from = i;
  14. int to = (i + portion) <= endIdx ? (i + portion) : endIdx;
  15.  
  16. threads.push_back( std::thread( [=,&fn]()
  17. {
  18. for ( int j = from; j < to; ++j )
  19. fn( j );
  20. } ) );
  21. }
  22. std::for_each( threads.begin(), threads.end(), []( std::thread& x )
  23. {
  24. x.join();
  25. } );
  26. }
  27. int main() {
  28. std::vector<unsigned int> v;
  29. for(unsigned int i = 0; i < 64; i++)
  30. {
  31. v.push_back(i);
  32. }
  33. auto func = [&v](size_t j) {
  34. v[j] = v[j]*v[j];
  35. };
  36. ParallelFor(0, v.size(), func, 4);
  37. for(unsigned int i = 0; i < v.size(); i++)
  38. {
  39. std::cout << v[i] << "\n";
  40. }
  41. return 0;
  42. }
Success #stdin #stdout 0s 36184KB
stdin
Standard input is empty
stdout
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729
784
841
900
961
1024
1089
1156
1225
1296
1369
1444
1521
1600
1681
1764
1849
1936
2025
2116
2209
2304
2401
2500
2601
2704
2809
2916
3025
3136
3249
3364
3481
3600
3721
3844
3969