Concurrent Programming Course note 3
Semaphore
Initialize how many permissions you will use.
acquire() will add one permission.
release() will remove one permission.
Permission must ≥ 0.
Semaphore solution for the MEP
- #criticalSection + permissions = 1
- #criticalSection = #acquires − #releases
Mutual exclusion: #criticalSection ≤ 1 since #permission ≥ 0. Absence of deadlock: It never happens that #permission = 0 and #criticalSection = 0
Java
public class Turnstile extends Thread {
static volatile int counter = 0; // keyword is recommended for variables that are shared
static Semaphore mutex = new Semaphore (1);
public void run() {
for(int i = 0; i < 50; i++){
mutex.acquire();
counter ++;
mutex.release();
System.out.println(id+"- In comes: "+i );
}
}
public static void main(String args[]) {
try{
Thread m1 = new Turnstile (1); m1.start();
Thread m2 = new Turnstile (2); m2.start();
} catch(Exception e){}
}
}Strong semaphore
Possibility of starvation is caused by the fact that blocked processes are placed in a set of processes. But this can be remedied by changing the set to be a queue.

