Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sem_init on OS X

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.

like image 690
Nippysaurus Avatar asked Sep 11 '09 23:09

Nippysaurus


People also ask

What is Sem_init in C?

The sem_init() function initializes an unnamed semaphore and sets its initial value. The maximum value of the semaphore is set to SEM_VALUE_MAX. The title for the semaphore is set to the character representation of the address of the semaphore.

What's the difference between Sem_init () and Sem_open ()?

h> int sem_init (sem_t *sem, int pshared, unsigned int value); sem_init is the equivalent of sem_open for unnamed semaphores. One defines a variable of type sem_t and passes its pointer as sem in the sem_init call. Or, one can define a pointer and allocate memory dynamically using malloc or a similar function call.

Is Sem_wait blocking?

Use sem_wait(3RT) to block the calling thread until the semaphore count pointed to by sem becomes greater than zero, then atomically decrement the count.

What does Sem_init return?

sem_init() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value.


2 Answers

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.

like image 79
Nippysaurus Avatar answered Sep 20 '22 23:09

Nippysaurus


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.

like image 33
Jess Bowers Avatar answered Sep 24 '22 23:09

Jess Bowers