The Code-Bin
Links
Home
Add your code!
All Listings
About
Latest Entry
Featured Scripts
Author's Website
Latest Entries
FFMPEG Thumbnail Scr...
PHP, 0.8KB
Jul. 29, 10:24pm
John
Z80 Assembler, 190 bytes
Feb. 17, 3:36am
John
Z80 Assembler, 176 bytes
Sep. 13, 2:19am
John
Z80 Assembler, 77 bytes
Sep. 13, 2:18am
John
Z80 Assembler, 209 bytes
Sep. 13, 2:17am
Mutual Exclusion Example
Posted by: Semaphore.java_Dispatcher.java | December 5, 2010 @ 9:28am
Java Code
[
Download
]
public class Semaphore { private int value; /** * In practice, this ArrayList would be declared as * ArrayList<Process>. */ private ArrayList queue; public Semaphore( int value ) { this.value = value; /* * In practice, this.queue would be declared with * new ArrayList<Process>. */ this.queue = new ArrayList(); } /** * In practice, the process parameter would be of type Process. */ public static void P( Object process ) { this.value--; if ( this.value < 0 ) { // must have been 0 or less before the decrement queue.add( process ); } } /** * In practice, the process parameter would be of type Process. */ public static void V( Object process ) { this.value++; if ( this.value <= 0 ) { // must have been negative before the increment queue.remove( process ); // a system call I made up System.addToReadyQueue( process ); } System.dispatch(); // dispatches the next process on the ready queue } } public class Dispatcher { public static void main( String[] args ) { Semaphore mutex = new mutex( 1 ); Process p1 = new Process(); Process p2 = new Process(); while ( System.notHalt() ) { // entry section mutex.P( p1 ); // mutex.value = 0 mutex.P( p2 ); // mutex.value = -1, mutex.queue = [p2] // critical section System.dispatch(); // dispatches p1, as p2 is in mutex.queue // exit section /* * mutex.value = 0, so p2 is taken off mutex.queue and * added to System.readyQueue, and the dispatcher runs * the next process on the ready queue, which is now p2 */ mutex.V( p1 ); /* * mutex.value = 1, so nothing happens because * mutex.value > 0 */ mutex.V( p2 ); } } }
Syntax Highlighting
[
Open in new window
]
Author Comments
This is only concept code and will not actually compile or execute.
Rating
4.62 / 8
32 Votes