Page 1 of 1

Semaphores

Posted: Wed Feb 15, 2006 12:00 am
by astrov
Hi,

this post is pertaining to my attempt in understanding semaphores through a given scenerio.

[you are sharing a small refrigerator with two roommates.

the current space in the refrigerator can only contain at most 4 cans of 'coke'.

you cannot purchase any can of 'coke' unless there is an empty slot in the refrigerator.

you cannot drink 'coke' if there is none.

write the pseudo-code using semaphores (wait() and signal()) to solve the synchornization problem.]

I am also trying to understand semaphores from the book 'operating system concepts by Silberschatz, Galvin & Gagne', albeit with difficulty.

Anyone glad to help? or perhaps provide simpler insights to semaphores?

Thank You very much.

Re: Semaphores

Posted: Wed Feb 15, 2006 12:00 am
by carbonBased
Semaphores can be thought of as, essentially, a number with a potential block associated with it.

I generally use Up() and Down() methods to make it easier. In your case, Down() == Wait() and Up() == Signal().

So, in one of the cases listed below, you need to synchronize access to the fridge such that people can only get coke is there is some. Here you would start with a semaphore with a value of 0, and whenever a coke is added to the fridge you Up() the semaphore.

When someone wants to take a coke from the fridge you Down() the semaphore. If the semaphore is at 0, it cannot be "downed." As such, it waits/blocks until someone adds a coke to the fridge (via an Up()).

The second portion of the problem can be managed via a semaphore that starts with an initial value of 4. If someone wishes to purchase a coke they must first Down() this semaphore. If the semaphore is at 0, this means there's no space in the first, and the semaphore will block/wait until someone removes a can from the fridge (implying an Up() of this semaphore).

--Jeff

Re: Semaphores

Posted: Thu Feb 16, 2006 12:00 am
by Da_Maestro
So...your pseudo code would be in two parts, drinkCoke and buyCoke

Code: Select all

void drinkCoke()
{
    wait( forCoke );
    takeFromFridge( "Coke" );
}


void buyCoke()
{
    buy( "Coke" );
    signal( greedyRoomMates, "There's coke in the fridge!" );
    putInFridge( "Coke" );
}


Re: Semaphores

Posted: Sat Feb 18, 2006 12:00 am
by astrov
hey thanks guys, i understand it now =)