java - Implement semaphores using the monitor concept -
i trying implement semaphores using monitor concept in java. i.e java class implements weak counting semaphore (using methods init, signal , wait)
can tell me if class correct (if not problem):
class mymonitor { int counter = 0; //init public mymonitor( int init ) { counter = init; } //signal public synchronized void s() { counter++; notify(); } //wait public synchronized void w() { if( counter == 0 ) { try { wait(); } catch(interruptedexception e) { } } counter--; } }
if correct, give me idea of how can test class.
it should (with while
, not if
):
class yourmonitor { int counter = 0; //init public mymonitor( int init ) { counter = init; } //signal public synchronized void s() { counter++; notifyall(); } //wait public synchronized void w() throws interruptedexception { while ( counter <= 0 ) { wait(); } counter--; } }
how test:
public class testyoursemaphore { private static final int cnt = 100000; private int x = 0; private yoursemaphore s = new yoursemaphore(); public void run() throws interruptedexception { thread t1 = new thread(new myrunnable()); thread t2 = new thread(new myrunnable()); thread t2 = new thread(new myrunnable()); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); // verify, x has correct value if (x != 3 * cnt) { throw new runtimeexception("race condition error!"); } system.out.println("finished"); } private class myrunnable implements runnable { @override public void run() { (int = 0; < cnt; i++) { //un-comment use semaphores //s.enter(); x = x + 1; //s.leave(); } } } }
- without semaphore, exception thrown time (almost).
- with suggested semaphore, exception not thrown.
- with semaphore, exception thrown (but not without semaphores).
the problem semaphore is:
- thread 1 has lock
- thread 2 , thread 3
wait()
ing - thread 1 calls
notifyall()
- thread 2 , 3 simultaneously enter critical section, bad :)
Comments
Post a Comment