sem_init on OS X

CMacosPthreadsSemaphore

C Problem Overview


I am working on some code which uses the pthread and semaphore libraries. The sem_init function works fine on my Ubuntu machine, but on OS X the sem_init function has absolutely no effect. Is there something wrong with the library or is there a different way of doing it? This is the code I am using to test.

sem_t sem1;
sem_t sem2;
sem_t sem3;
sem_t sem4;
sem_t sem5;
sem_t sem6;

sem_init(&sem1, 1, 1);
sem_init(&sem2, 1, 2);
sem_init(&sem3, 1, 3);
sem_init(&sem4, 1, 4);
sem_init(&sem5, 1, 5);
sem_init(&sem6, 1, 6);

The values appear to be random numbers, and they do not change after the sem_init call.

C Solutions


Solution 1 - C

Unnamed semaphores are not supported, you need to use named semaphores.

To use named semaphores instead of unnamed semaphores, use sem_open instead of sem_init, and use sem_close and sem_unlink instead of sem_destroy.

Solution 2 - C

A better solution (these days) than named semaphores on OS X is Grand Central Dispatch's dispatch_semaphore_t. It works very much like the unnamed POSIX semaphores.

Initialize the semaphore:

#include <dispatch/dispatch.h>
dispatch_semaphore_t semaphore;
semaphore = dispatch_semaphore_create(1); // init with value of 1

Wait & post (signal):

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
...
dispatch_semaphore_signal(semaphore);

Destroy:

dispatch_release(semaphore);

The header file is well documented and I found it quite easy to use.

Solution 3 - C

If you look at the implementation of sem_init in the source then it just returns an error, while some of the other bsd fns like sem_open still have implementation.

Both the "deprecated" posix fns and libdispatch/GCD call from userspace using fns like semphore_create and semaphore_wait. You can use these directly if you want an old-style sema that always uses the kernel/OS, but you're better with ones like from GCD that uses atomic counters internally and only calls the kernel/OS if it has to wait.

https://github.com/apple/darwin-xnu/blob/a1babec6b135d1f35b2590a1990af3c5c5393479/bsd/kern/posix_sem.c

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNippysaurusView Question on Stackoverflow
Solution 1 - CNippysaurusView Answer on Stackoverflow
Solution 2 - CJess BowersView Answer on Stackoverflow
Solution 3 - CG HuxleyView Answer on Stackoverflow