title: why doesn't sem_wait block
body: <pre><code>static int res1 = 0;
  static int res2 = 0;
  static int res3 = 0;
  
  static int counter = 0;
  static sem_t sem;
  
  
  
  void * func_thread1(void *p)
  {
      sleep(2);
      res1 = 1;
      printf("func_thread1\n");
      sem_post(&amp;sem);
      return NULL;
  }
  
  void * func_thread2(void *p)
  {
      sleep(2);
      res2 = 2;
      printf("func_thread2\n");
      sem_post(&amp;sem);
      return NULL;
  }
  
  void * func_thread3(void *p)
  {
      sem_wait(&amp;sem);
      sem_wait(&amp;sem);
      res3 = res1 + res2;
      printf("func_thread3\n");
      return NULL;
  }
  
  
  
  
  void main()
  {
      sem_init(&amp;sem, 0, counter);
      pthread_t pd1, pd2, pd3;
      pthread_create(&amp;pd1, NULL, func_thread1, NULL);
      pthread_create(&amp;pd2, NULL, func_thread2, NULL);
      pthread_create(&amp;pd3, NULL, func_thread3, NULL);
  
      //pthread_join(pd3, NULL);
  
      printf("main_thread\n");
      printf("%d", res3);
  }
  </code></pre>
  
  <p>I'm trying to understand how semaphore works.<br>
  I'm trying to make the <code>td3</code> block to wait for the <code>td1</code> and the <code>td2</code>.<br></p>
  
  <p>In my opinion, the <code>sem_wait</code> will block twice. If the <code>sem_post</code>s in <code>func_thread1</code> and in <code>func_thread2</code> are executed, <code>func_thread3</code> could continue.<br></p>
  
  <p>However, it doesn't work unless I add <code>pthread_join(td3, NULL)</code> in <code>main</code>. I think the join is not necessary because <code>sem_wait</code> can block.<br></p>
  
  <p>So <code>pthread_join</code> is necessary or I use semaphore incorrectly?</p>