Reputation: 65
This is what I understood about counting semaphores
P1 enters critical state
calls wait()
wait()
{
semaphore--;
if (semaphore<=0)
block;
else
execute the c.s
after execution in c.s calls signal();
}
signal()
{
semaphore++;
If(blocked process exists)
allow first process that is waiting and P1 leaves c.s
}
If I am correct then tell me what happens in the case of binary semaphore that can have only 1 and 0 as values. Or is the implementation of binary semaphore different from this?
Upvotes: 0
Views: 737
Reputation: 965
A few things here :
First try to understand what a semaphore is built to do. Constructs like semaphores are built to help achieve concurrency in programs. Ask yourself - what is it that you want to achieve? Synchronization? Mutual exclusion? Both?
Depending on the answer to that question, the way you use your semaphore will completely change. Understanding the fundamentals of what a semaphore does is vital to understanding the difference between a binary and counting semaphore.
I've explained the difference between a binary/counting semaphore in detail here, this will be useful to you: https://stackoverflow.com/a/22582997/2112500 Go through this completely, slowly, step by step, and make sure you understand the fundamentals. Your code above, while telling me that you've understood (to a limited extent) what happens inside a semaphore, doesn't necessarily tell me that you know how to use one.
for example, in this bit of pseudo code :
else
execute the c.s
after execution in c.s calls signal();
You're signalling from inside the wait - that's not quite going to work the way you want it to.
And again, here :
allow first process that is waiting and P1 leaves c.s
I don't think you quite grasp where the semaphore ends, and its use in a thread begins. I would suggest starting with that link above. Then proceed to try and use semaphores in some simple programs to achieve synchronization and mutual exclusion.
Upvotes: 1