Good afternoon. I work with semaphores, for mysterious reasons for me, even if I immediately try to use it after initializing the semaphore, it fails, sem_trywait returns -1.

for(int i = 0; i< 5; i++) { sem_init(&utensils[i], 0, 1); sem_trywait(&utensils[i]); //returns -1 always! //create new thread processes for the philosophers pthread_create(&phs[i], NULL, philosopher, &num[i]); //check if the threads are created assert(!(phs[i] == 0)); } 
  • I see, this game - (void*) &philosopher - continues to wander from option to option. - AnT
  • does work. And how should you? - Maria Lifshits
  • one
    What platform are you working on? Specific numbers in errno meaningless without specifying a platform. 78 on many platforms is ENOSYS , i.e. "function not implemented", i.e. semaphores in this implementation are simply not supported at all. Open <errno.h> and see what 78 on your platform. - AnT
  • one
    Or call perror after initialization to print a meaningful error message. - AnT
  • one
    the code in question is correct .... it is worth extending it to a full-fledged minimum compiled example ... - Fat-Zer

1 answer 1

So. The code is correct, there are no errors with it. The point was that I use the Apple operating system - in which the semaphores are deprecated, so initialization was not performed. When using Linux - no problem.