Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_mutex_init vs sem_init (Unshared)

I am looking at changing some code that I would like to run on linux, unix, and OSX. There are some calls in the code for a sem_init, but the pshared value is set to zero. I did some reading in the Rochkind book on unix programming and he basically said that sem_init that is not shared is the same as a pthread_mutex_init because it's acting in an in-memory, binary fashion.

The question is - am I safe to change these sem_init's 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 guess the other two do. I don't really want to have a separate compile flag to #ifdef(__APPLE__) or something either.

Thanks

like image 457
Derek Avatar asked Dec 12 '22 23:12

Derek


2 Answers

mutexes and semaphore have different semantics. A mutex must be unlocked by the same thread that has taken the lock. So lock / unlock must always come in pairs in the same thread.

A semaphore is much more flexible in that another thread can post a token that another thread consumes. They are e.g commonly used to implement producer / consumer patterns. So you'd have to check the program that you want to port if it fits to the restricted semantic of mutexes.

like image 139
Jens Gustedt Avatar answered Jan 03 '23 20:01

Jens Gustedt


The semantics of mutexes and semaphores are different. It is true that a non-shared semaphore is equivalent to a mutex if it is only used as a binary semaphore, i.e. if its value is never greater than 1. However, this is something you need to determine from your code's logic not how it is initialized. If you are sure that the semaphore is only used as a binary semaphore then a pthread mutex is a perfect replacement. If not you can either use sem_open() for portability or write a wrapper that emulates semaphores using pthread mutexes and condition variables.

like image 35
torrey.lyons Avatar answered Jan 03 '23 18:01

torrey.lyons