Where do we really need a set of System v Semaphores?

442 views Asked by At

Every time I read the description of semget: The semget() system call returns the semaphore set identifier associated with the argument key., I wonder where do we really need set of System V Semaphores.

I always give the nsems parameter as 1 because most of the times I require a single semaphore. Even if I don't need a binary semaphore why would I create a set of 5-6 semaphores (say).

and what if a process creates a set of 6 semaphores associated with a single key and another tries to do semget on the same key asking for just 3 semaphores. Also aren't all those 6 semaphores 6 individual binary semaphores. I am thirsty and looking for an answer to this question for 2 months (not continuously of-course).

I am sorry if this question seems to be the most stupid one but unless I get an example of the real use of the set of semaphores this doubt will remain in my mind. I have tried to search for an example C code where someone is using a set of semaphore but I could not find one.

I would be really really thankful to you guys if you could help me out on this. Thanks a tonne in advance.

3

There are 3 answers

2
Jonathan Leffler On

I work on a DBMS that uses one semaphore for each of of a set of cooperating processes that work on the same data, cooperating via shared memory. Having to allocate those one at a time would be a nuisance; having a semaphore set with 20 (or whatever) semaphores in it is very convenient.

2
BMitch On

The most typical situation I know of for a semaphore is when you have a queue of data being processed by one or more processing threads. Each thread will decrease the semaphore for each entry removed from the queue, and as new data is put in the queue, the semaphore is incremented. Then all you need to do is wait on the semaphore rather than constantly polling for an update.

0
Constantinos Georgiou On

I used a set of semaphores in an assignment in my Operating Systems course at my university.

The assignment was to create a server that spawns clients. The clients could send requests and receive responses from the server. Only one client at a time could send a request to the server.

So I used three semaphores:

  • 1 as a mutex (initialized to one) used exclusively between the clients
  • 1 for requests, between a client and the server.
  • 1 for responses, between the server and a client