sem_init(...): What is the pshared parameter for?

Frank V picture Frank V · Aug 18, 2009 · Viewed 15.1k times · Source

In a graduate class, we've had to use semaphores to accomplish work with threads.

We were directed to use sem_init along with a bunch of other sem_* procedure but we were not given much information about the details of each of these sem_* methods.

The prototype (and header file) of sem_init is the following:

#include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value);

but I don't understand what the pshared value is used for. According to opengroup.org:

If the pshared argument has a non-zero value, then the semaphore is shared between processes; in this case, any process that can access the semaphore sem can use sem for performing sem_wait(), sem_trywait(), sem_post(), and sem_destroy() operations.

but I guess I don't understand the difference between say 1,2, 10, 25, 50000, etc. I think it is saying that if the value is 0 then the semaphore is not shared. (But then, what is the point?)

How do I appropriately use this pshared parameter?

Answer

quark picture quark · Aug 18, 2009

The GLIBC version of sem_init (what you get if you man sem_init on Linux) has this to say:

"The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes."

So pshared is a boolean value: in practice meaningful values passed to it are false (0) and true (1), though any non-0 value will be treated as true. If you pass it 0 you will get a semaphore that can be accessed by other threads in the same process -- essentially an in-process lock. You can use this as a mutex, or you can use it more generally for the resource-counting properties of a semaphore. Arguably if pthreads supported a semaphore API you wouldn't need this feature of sem_init, but semaphores in Unix precede pthreads by quite a bit of time.

It would be better if the boolean was some kind of enumeration (e.g. SEM_PROCESS_PRIVATE vs SEM_PROCESS_SHARED), because then you wouldn't have had this question, but POSIX semaphores are a fairly old API as these things go.