title: How to dynamically allocate work to threads
body: <p>I am trying to write code for finding if pairwise sums are even or not(among all possible pairs from 0 to 100000). I have written code using pthreads where the work allocation is done statically. Here is the code</p>
  <pre><code>#include&lt;iostream&gt;
  #include&lt;chrono&gt;
  #include&lt;iomanip&gt;
  #include&lt;pthread.h&gt;
  
  
  using namespace std;
  #define MAX_THREAD 4
  
  vector&lt;long long&gt; cnt(MAX_THREAD,0);
  long long n = 100000;
  int work_per_thread;
  
  void *count_array(void* arg)
  {
      int t = *((int*)arg);
      long long sum = 0;
      int counter = 0;
      for(int i = t*work_per_thread + 1; i &lt;= (t+1)*work_per_thread; i++)
        for(int j = i-1; j &gt;= 0; j--)
        {
           sum = i + j;
           if(sum%2 == 0)
               counter++;
        }
      cnt[t] = counter;
      cout&lt;&lt;&quot;thread&quot;&lt;&lt;t&lt;&lt;&quot; finished work&quot;&lt;&lt;endl;
      return NULL;
  }
  
  
  int main()
  {
    pthread_t threads[MAX_THREAD];
    vector&lt;int&gt; arr;
    for(int i = 0; i &lt; MAX_THREAD; i++)
      arr.push_back(i);
    long long total_count = 0;
    work_per_thread = n/MAX_THREAD;
  
    auto start = chrono::high_resolution_clock::now();
    for (int i = 0; i &lt; MAX_THREAD; i++)
        pthread_create(&amp;threads[i], NULL, count_array, &amp;arr[i]);
  
    for (int i = 0; i &lt; MAX_THREAD; i++)
        pthread_join(threads[i], NULL);
  
    for (int i = 0; i &lt; MAX_THREAD; i++)
        total_count += cnt[i];
  
    cout &lt;&lt; &quot;count is &quot; &lt;&lt; total_count &lt;&lt; endl;
  
    auto end = chrono::high_resolution_clock::now();
    double time_taken = chrono::duration_cast&lt;chrono::nanoseconds&gt;(end - start).count();
    time_taken *= 1e-9;
    cout &lt;&lt; &quot;Time taken by program is : &quot; &lt;&lt; fixed &lt;&lt; time_taken &lt;&lt; setprecision(9)&lt;&lt;&quot; secs&quot;&lt;&lt;endl;
  
    return 0;
  }
  </code></pre>
  <p>Now I want to do the work allocation part dynamically. To be specific, let's say I have 5 threads. Initially I give the threads a certain range to work with, let's say thread1 works on all pairs from 0-1249, thread2 from 1250-2549 and so on. Now as soon as a thread completes its work I want to give it a new range to work on. This way no threads will be idle for most of the time, like was in the case of static allocation.</p>