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
psharedargument has a non-zero
value, then the semaphore is shared
between processes; in this case, any
process that can access the semaphore
semcan usesemfor performing
sem_wait(),sem_trywait(),sem_post(),
andsem_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?
The GLIBC version of
sem_init(what you get if youman sem_initon Linux) has this to say:So
psharedis a boolean value: in practice meaningful values passed to it arefalse(0) andtrue(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 ofsem_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_PRIVATEvsSEM_PROCESS_SHARED), because then you wouldn’t have had this question, but POSIX semaphores are a fairly old API as these things go.