Interprocess mutex with pthreads
Solution 1:
The following example demonstrates the creation, use and destruction of a Pthread interprocess mutex. Generalizing the example for multiple processes is left as an exercise for the reader.
#include <pthread.h>
pthread_mutex_t shm_mutex;
int main(void)
{
int err;
pthread_mutexattr_t attr;
err = pthread_mutexattr_init(&attr); if (err) return err;
err = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); if (err) return err;
err = pthread_mutex_init(&shm_mutex, &attr); if (err) return err;
err = pthread_mutexattr_destroy(&attr); if (err) return err;
err = pthread_mutex_lock(&shm_mutex); if (err) return err;
err = pthread_mutex_unlock(&shm_mutex); if (err) return err;
err = pthread_mutex_destroy(&shm_mutex); if (err) return err;
return 0;
}
Solution 2:
Use a POSIX semaphore initialized to (See below) Use 1
instead.sem_init
for unnamed semaphores or sem_open
for named ones.
sem_t sem;
/* initialize using sem_init or sem_open */
sem_wait(&sem);
/* critical region */
sem_post(&sem);
Many years after initially posting this answer, it has to be updated.
Mutexes should actually be used instead of semaphores. R and kuga's comments (copied verbatim below) explain why. In particular I find kuga's mention that mutexes can only be post
ed by their locking thread most compelling.
R
sem_init requires a nonzero pshared argument to be shared, just like a mutex would require the pshared attribute. There's no reason to prefer semaphores over mutexes for this, and in fact mutexes would be better because you could use a robust mutex which allows you to handle the (very real!) case where one process dies while holding the lock.
kuga
Additionally to R..`s post, a mutex can only be posted by the thread that locks it. This is often required and a semaphore does not provide this feature. So this is not the correct answer, Jeff´s answer should be flagged as the correct answer.