title: Assigning unique sources to a thread pool in C
body: <p>I use this <a href="https://github.com/Pithikos/C-Thread-Pool" rel="nofollow noreferrer">library</a> for creating a queued pool of <code>pthread</code>. The thread is decided by the OS, but we know that we always have 4 jobs (in the below case) running simultaneously as long as the queue is full.</p>
  <p>If each job uses one source from 4 available sources, I want to guarantee that all 4 sources are used at the same time. Avoiding a source to be used twice while another is not used in a time.</p>
  <p>I came with this idea to use an array keeping track of used sources</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;unistd.h&gt;
  #include &quot;thpool.h&quot;
  
  int sources[4] = {0}; // 0 Source is available 1 Source is occupied
  
  void task(void *arg)
  {
      int source;
      for (int i = 0; i &lt; 4; i++)
      {
          if (sources[i] == 0)
          {
              sources[i] = 1; // Occupying the source
              source = i; // Assining the source
              break;
          }
      }
      sleep(1);
      printf(&quot;Thread %u working on %d with source %d\n&quot;, (int)pthread_self(), (int)arg, source);
      sources[source] = 0; // Making the source available again
  }
  
  int main()
  {
  
      puts(&quot;Making threadpool with 4 threads&quot;);
      threadpool thpool = thpool_init(4);
  
      puts(&quot;Adding 40 tasks to threadpool&quot;);
      int i;
      for (i = 0; i &lt; 40; i++)
      {
          thpool_add_work(thpool, task, (void *)(uintptr_t)i);
      };
  
      thpool_wait(thpool);
      puts(&quot;Killing threadpool&quot;);
      thpool_destroy(thpool);
  
      return 0;
  }
  </code></pre>
  <p>This works well in basic tests, but I am not sure about reliability since we have no lock on the process of updating the <code>sources</code> array.</p>