title: Grouping threads in C
body: <p>Two producers manufacture goods of type A and type B in a multithreading interview question. There are an arbitrary number of both categories of producers (the number will ensure that it is possible to pack two types of products with the given constraints). Producers' products might be packaged in two different ways:</p>
  <p>a) 2 product-A and 2 product-B<br>
  b) 4 product-A<br>
  c) 4 product-B<br></p>
  <p>If products are manufactured in the following order: A(1) A(2) A(3) B(1) B(2)..., then A(1), A(2), B(1), B(3) must be packed together and their individual threads must be terminated, while A(3) must wait to be packed in alternative an or b.</p>
  <hr />
  <p>So, because the packaging methods of manufacturers A and B varied, I came up with the idea of creating two independent functions for them. In order for producer A to meet any of the packing criteria, at least two A's must be present, and the same is true for producer B. As a result, the first semaphore should be:</p>
  <pre><code>int
  main(int argc, const char *argv[])
  {
      // ...
  
      pthread_barrier_init(&amp;barrier_for_producer_a, NULL, 2);
      pthread_barrier_init(&amp;barrier_for_producer_b, NULL, 2);
  
      // ...
  }
  
  void *
  producer_a_routine()
  {
      pthread_barrier_wait(&amp;barrier_for_producer_a);
      // ...
  }
  
  void *
  producer_b_routine()
  {
      pthread_barrier_wait(&amp;barrier_for_producer_b);
      // ...
  }
  </code></pre>
  <p>But after that, the threads should sleep whilst also simultaneously monitoring if the other two criteria are met, or the thread that causes any of the conditions to be met should wake the appropriate producer routines, but I had no clue how to achieve that and still don't. So, what would be the best course of action here?</p>