Mutual Exclusion using Semaphores

Mutual Exclusion using Semaphores

class Loop implements Runnable {

Semaphore lock_;

public Loop (Semaphore lock) {lock_=lock;}

public void run() {

while(true) {

// acquire mutual exclusion

lock_.down();

// critical section

lock_.up();

// mutual exclusion released

}

}

}

Mutual exclusion can be obtained explicitly using Semaphores. In general, it is better practice to use the Java synchronized constructs. For mutual exclusion, the semaphore must be initialised to 1.

Demo

Previous slide Next slide Back to the first slide View Graphic Version