John Vorwald wrote:Try a semaphore with one permit, look for producer / consumer examples...
Semaphore is not perfect solution to this problem. Semaphore is to guarantee that specified number of threads can only enter into restricted area but not their ordering.
Below code will work with high sleep time 100 but if you will reduce sleep from 100ms to 1ms, you can notice a difference.
without semaphore, cyclic barrier, the following code produced desired result for several runs.
Joined: Jun 27, 2011
Harsha Smith wrote:without semaphore, cyclic barrier, the following code produced desired result for several runs.
This code is not perfect. Check results given below. Also what if i don;t want to put any sleep ? Above mentioned code execution is entirely based on Thread scheduler and it's not guaranteed to work always.
Try your code with just 3 threads and you will see difference.