For our project we will be implementing semaphore using P() and V() in java. Before I can do that I need to understand what TestandSet and Enabling/Disabling interrupts to. I understand test and set alone without the addition of semaphores but I do not understand it when semaphores are being implemented. My knowledge is with Test and Set with two threads for example you have a global variable occupied and it is true if a thread is in its critical section. The thread can enter its critical section based on its local variable mustWait. Now lets say Thread one wants to enter and mustwait=true then it repeatedly calls testandset(mustwait, occupied) until occupied is false. When the other thread sets occupied to false after leaving its critical section, when Thread one calls testandset(mustwait, occupied), occupied would be set to false which is copied into mustwait allowing thread one to enter its critical section.
Now with semaphores understand when a thread wants to enter its critical section P(S) is called whereif S>0 S=S-1; Else The thread is placed on the waiting queue. //when it is done executing it calls V(S) which says: If any threads are waiting on S Resume with the next waiting thread in the queue Else S=S+1;
Can someone explain these two implementations of Semaphores with Test and Set and Enabling/disabling interrupts?
Test and Set
typedef struct { int count; queue q; int t; } SEMAPHORE; P(s) SEMAPHORE *s; { Disable interrupts; while (TAS(s->t) != 0) /* do nothing */; if (s->count > 0) { s->count = s->count-1; s->t = 0; Enable interrupts; return; } Add process to s->q; s->t = 0; Redispatch; } V(s) SEMAPHORE *s; { Disable interrupts; while (TAS(s->t) != 0) /* do nothing */; if (s->q empty) { s->count += 1; } else { Remove first process from s->q; Wake it up; } s->t = 0; Enable interrupts; }
Enabling/Disabling Interrupts
Using Enable/Disable Interrupts class Semaphore { int number = 0; } Semaphore:() { Disable interrupts; while (number == 0) { Enable interrupts; Disable interrupts; } number = number - 1; Enable interrupts; } Semaphore::V() { Disable interrupts; number++; Enable interrupts; }