Search code examples
cposixsemaphoremultiple-processes

what is the pshared value of a semaphore if I used sem_open() instead of sem_init()?


I am currently working on the dining philosophers problem using semaphores and processes, and I used sem_open() function to create semaphores instead of sem_init(). And since the sem_open() doesn't take the pshared value as a parameter. Could somebody give me a good explanation how the semaphores are shared between processes when using sem_open()? I thought that maybe because the semaphore is opened in the file system but some more clarification would be most appreciated .


Solution

  • Under Linux/glibc, POSIX semaphores are implemented with the pthread mutexes which are based on the futexes. The pshared parameter relates to the mutex attribute passed to pthread_mutexattr_setpshared. The possible values are:

    • PTHREAD_PROCESS_PRIVATE for mutexes internal to the process (this is the default in the pthread library);
    • PTHREAD_PROCESS_SHARED for mutexes shared between any threads that have access to the memory containing the object, including threads in different processes.

    When a semaphore is created with sem_open(), it is considered shareable between processes and threads. That is to say, it behaves like sem_init() when we set pshared to non-zero.
    Internally, sem_open() creates a file in /dev/shm into which a sem_t structure is stored. The file is mapped in the calling process memory with a call to mmap(NULL, sizeof (sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) where fd is the file descriptor of the opened file. So, this is how the semaphore is shared between processes as they all map the same file content in their address space.
    As a side note, the value returned by sem_open() is the address of the memory mapped sem_t structure from the underlying file.