Semaphores

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
astrov
Posts: 2
Joined: Wed Feb 15, 2006 12:00 am

Semaphores

Post 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.
User avatar
carbonBased
Member
Member
Posts: 382
Joined: Sat Nov 20, 2004 12:00 am
Location: Wellesley, Ontario, Canada
Contact:

Re: Semaphores

Post 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
Da_Maestro
Member
Member
Posts: 144
Joined: Tue Oct 26, 2004 11:00 pm
Location: Australia

Re: Semaphores

Post 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" );
}

Two things are infinite: The universe and human stupidity. But I'm not quite sure about the universe.
--- Albert Einstein
astrov
Posts: 2
Joined: Wed Feb 15, 2006 12:00 am

Re: Semaphores

Post by astrov »

hey thanks guys, i understand it now =)
Post Reply