1

As far as I know the below code should result in a deadlock and NOT print out "hello world". However, when I compile on my computer (Macbook Air late 2013, 10.9.2) with gcc, the code unexpectedly prints "hello world" and finishes execution.

Why does the below code not result in deadlock?

#include <stdio.h>
#include <semaphore.h>
int main() {
  sem_t prod_slots;
  sem_init(&prod_slots, 0, 0);
  sem_wait(&prod_slots);
  sem_wait(&prod_slots);
  sem_wait(&prod_slots);
  printf("%s\n", "hello world");
  return 1;
}
Vivek Seth
  • 177
  • 1
  • 6
  • 2
    Does the return value of sem_wait or sem_init offer any clues? – Pete Baughman Apr 15 '14 at 20:28
  • 1
    Some versions of OSX have the "feature" to "implement" `sem_init` with a function that always returns an error. This seems to be their idea of POSIX compliance. – Jens Gustedt Apr 15 '14 at 20:32
  • If you switch to named semaphores (i.e. `sem_open`, `sem_destroy`, `sem_unlink`) it will work as expected. I remain curious as to *why* OSX found unnamed semaphores too burdensome to implement. – Duck Apr 15 '14 at 20:50
  • @Duck That's what it was. If you put your comment as an answer I will select it as correct. – Vivek Seth Apr 15 '14 at 22:18

0 Answers0