Pthread_mutex_init vs sem_init (Unshared)

I am looking at changing code that I would like to run on Linux, Unix, and OSX. There are some calls in the code for sem_init, but the value of pshared is zero. I read in Rochkind's book on unix programming, and he basically said that sem_init, which is not generic, is the same as pthread_mutex_init because it acts in binary form in memory.

Question: can I change this sem_init to pthread_mutex_init or use sem_open to get a more portable version of this code?

OSX does not support unnamed semaphores, but I think the other two. I really don't want to have a separate compilation flag for #ifdef(__APPLE__) or something else.

thanks

+4
source share
3 answers

mutexes and semaphores have different semantics. The mutex must be unlocked by the same thread that occupied the lock. Therefore, locking / unlocking should always fall into pairs in the same thread.

A semaphore is much more flexible, since another thread can send a token that another thread consumes. They, for example, are commonly used to implement producer / consumer models. Therefore, you will need to check the program that you want to port if it suits the limited semantics of mutexes.

+8
source

The semantics of mutexes and semaphores are different. It is true that a non-generic semaphore is equivalent to a mutex if it is used only as a binary semaphore, i.e. If its value never exceeds 1. However, this is what you need to determine from your code logic, and not how it is initialized. If you are sure that the semaphore is used only as a binary semaphore, then the pthread mutex is an ideal replacement. If not, you can use sem_open () for portability, or write a wrapper that emulates semaphores using pthread mutexes and variable conditions.

+2
source

Switching to mutexes should be safe in this case. If only one thread can enter this critical section at a time, you actually have a mutex, regardless of whether it is written as a semaphore or not. However, depending on how the functions are implemented by the OS, you may get different performance characteristics. This is not something that I would lose sleep, but still something that could be forgotten during testing.

+1
source

All Articles