views:

408

answers:

2

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?

A: 

I would say that there is no significant difference between the value s 1, 2, 5 and so on with respect to the shared parameter. Probably it is written that way because when the API was first created, C did not have boolean types.

1800 INFORMATION
So does that make it an outdated API?
Sneakyness
I dunno - there is value sometimes in having the use of an older "tried and tested" API as well. You'd have to look at it from the point of view of things like efficiency and obvious security flaws to say if it was really outdated or not
1800 INFORMATION
Sneakyness: Yes and no. No in that Pthreads, the more modern choice, doesn't seem to have a semaphore implementation, so for those cases where you want semaphores that's the API you'd need to use. Yes, in that for most cases mutexes and conditions will do just fine in place of semaphores.
quark
+2  A: 

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.

quark
Awesome answer, thank you for the explanation.
Frank V
You're most welcome. Thank you for the compliment :).
quark