pthread_mutex_init vs sem_init (Unshared)
c, macos, pthreads, semaphore, unix
Solution
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.
Problem
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