java - Result of variables using Semaphore -
semaphore s = new semaphore (0); int x = 7; int y = 1; 1.1 s.acquire(); 2.1 s.release(); 2.2. s.release(); 1.2 s.aquire(); 2.3 s.acquire(); 1.3 int tmp = x; 2.4 int tmp = y; 1.4 s.release(); 2.5 s.release(); 1.5. tmp = tmp * 2; 2.6 tmp = tmp * 3; 1.6. s.acquire(); 2.7 s.acquire(); 1.7 y = tmp + 1; 2.8 x = tmp + 1; 1.8. s.release(); 2.9 s.release();
i have trouble getting result of these variables x , y, if these 2 threads run parallel.
the semaphore has 0 permits? possible output here should x=7, y=1, shouldn't it?
i don't understand nested acquires() , releases(). result of x , y ifsemaphore have 2 permits?
since there no delays in code, can run in many ways, depending on cpu faster, or how os schedules threads (e.g. in single-cpu system):
2.1 s.release(); 1 permit 2.2 s.release(); 2 permits 1.1 s.acquire(); 1 permit 1.2 s.acquire(); 0 permits 1.3 int tmp = x; 1.4 s.release(); 1 permit 1.5 tmp = tmp * 2; 1.6 s.acquire(); 0 permits 1.7 y = tmp + 1; 1.8 s.release(); 1 permit 2.3 s.acquire(); 0 permits 2.4 int tmp = y; 2.5 s.release(); 1 permit 2.6 tmp = tmp * 3; 2.7 s.acquire(); 0 permits 2.8 x = tmp + 1; 2.9 s.release(); 1 permit
or:
2.1 s.release(); 1 permit 2.2 s.release(); 2 permits 2.3 s.acquire(); 1 permit 2.4 int tmp = y; 2.5 s.release(); 2 permits 2.6 tmp = tmp * 3; 2.7 s.acquire(); 1 permit 2.8 x = tmp + 1; 2.9 s.release(); 2 permits 1.1 s.acquire(); 1 permit 1.2 s.acquire(); 0 permits 1.3 int tmp = x; 1.4 s.release(); 1 permit 1.5 tmp = tmp * 2; 1.6 s.acquire(); 0 permits 1.7 y = tmp + 1; 1.8 s.release(); 1 permit
what cannot happen, steps 1.3 , 2.4 run in parallel. there not enough permits that.
2.1 s.release(); 1 permit 1.1 s.acquire(); 0 permits 2.2 s.release(); 1 permit 1.2 s.acquire(); 0 permits 1.3 int tmp = x; <blocked> 1.4 s.release(); <blocked> 1 permit 2.3 s.acquire(); 0 permits 2.4 int tmp = y; 2.5 s.release(); 1 permit 1.5 tmp = tmp * 2; 2.6 tmp = tmp * 3; 2.7 s.acquire(); 0 permits <blocked> 2.8 x = tmp + 1; <blocked> 2.9 s.release(); 1 permit 1.6 s.acquire(); 0 permits 1.7 y = tmp + 1; 1.8 s.release(); 1 permit
there many other ways these 2 threads can interleaved.
Comments
Post a Comment