title: Dividing work between fixed number of threads with pthread
body: <p>I have <code>n</code> number of jobs, which there is no shared resource between them, and <code>m</code>threads. I want to efficiently divide number of jobs in threads in such a way that there is no idle thread untill everything is processed? </p>
  
  <p>This is a prototype of my program:</p>
  
  <pre><code>class Job {
      //constructor and other stuff
      //...
  
      public: doWork();
  };
  
  struct JobParams{
    int threadId;
    Job job;
  };
  
  void* doWorksOnThread(void* job) {
      JobParams* j = // cast argument
      cout &lt;&lt; "Thread #" &lt;&lt; j-&gt;threadId &lt;&lt; " started" &lt;&lt; endl;
      j-&gt;job-&gt;doWork();
      return (void*)0;
  }
  </code></pre>
  
  <p>Then in my main file I have something like:</p>
  
  <pre><code>int main() {
    vector&lt;Job&gt; jobs; // lets say it has 17 jobs
    int numThreads = 4;
  
    pthread_t* threads = new pthread_t[numThreads];
    JobParams* jps = new JubParams[jobs.size()];
  
    for(int i = 0; i &lt; jobs.size(); i++) {
      jps[i]-&gt;job = jobs[i];        
    }
  
    for(int i = 0; i &lt; numThread; i++) {
      pthread_create(&amp;t[i], null, doWorkOnThread, &amp;jps[0])
    }
  
    //another for loop and call join on 4 threads...
  
    return 0;
  }
  </code></pre>
  
  <p>how can I efficiently make sure that there is no idle thread until all jobs are completed?</p>