Advertisement
Guest User

Untitled

a guest
Jul 4th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. // this will split the work between all available threads
  2. // if chunk_count is -1, default number of chunks will be computed
  3. void JobQue::parallel_for ( int from, int to, const JobChunk & chunk, int chunk_count, int step )
  4. {
  5. if ( from >= to )
  6. return;
  7. // so the idea here is that if say 1 thread is busy
  8. // we don't pay 2x time. smaller chunks are more evenly distributed
  9. if ( chunk_count==-1 )
  10. chunk_count = mThreadCount * 4;
  11. // adjust step
  12. step = max ( ( to - from + 1 ) / chunk_count, step );
  13. int numChunks = (to - from + step) / step;
  14. // if only one chunk
  15. if ( numChunks==1 )
  16. {
  17. chunk(from, to);
  18. return;
  19. }
  20. // results
  21. int onMainThread = max ( (numChunks + mThreadCount) / (mThreadCount+1), 1 );
  22. int onThreads = numChunks - onMainThread;
  23. vector<JobStatus> status(onThreads);
  24. // que parallel ones
  25. for ( int ch = 0; ch < onThreads; ++ch )
  26. {
  27. int i0 = from + ch * step;
  28. int i1 = min(i0 + step, to);
  29. push([=,&chunk,&status](){
  30. PROFILE_BLOCKI("Main","PFor",0xff3f3f3f);
  31. chunk(i0, i1);
  32. status[ch].Notify();
  33. });
  34. }
  35. // run the tail
  36. for ( int ch = onThreads; ch < numChunks; ++ch )
  37. {
  38. int i0 = from + ch * step;
  39. int i1 = min(i0 + step, to);
  40. chunk(i0, i1);
  41. }
  42. // and wait for them (but last one)
  43. {
  44. PROFILE_BLOCKI("Main","WaitForPFor",0xffff0000);
  45. for ( int i=0; i<onThreads; ++i)
  46. status[i].Wait();
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement