Implementing a Barrier

This lesson discusses how a barrier is implemented in Ruby.

We'll cover the following...

Implementing a Barrier

A barrier can be thought of as a point in the program code, which all or some of the threads need to reach before any one of them is allowed to proceed further.

widget

Solution

A barrier allows multiple threads to congregate at a point in code before any one of the thread is allowed to move forward. Python and most other languages provide libraries that make barrier construct available for developer use. Even though we are re-inventing the wheel but this makes for a good interview question.

We can immediately realize that our solution will need a count variable to track the number of threads that have arrived at the barrier. If we have n threads, then n-1 threads must wait for the nth thread to arrive. This suggests we have the n-1 threads execute the wait method and the nth thread wakes up all the asleep n-1 threads.

Below is the code:

Press + to interact
class Barrier
def initialize(totalThreads)
@count = 0
@totalThreads = totalThreads
@mutex = Mutex.new
@cv = ConditionVariable.new
end
def await
@mutex.synchronize do
# increment the counter whenever a thread arrives at the barrier
@count = @count + 1
# if you are the nth thread
if (@count == @totalThreads)
# wake up all the threads
@cv.broadcast
# remember to reset count so that barrier can be reused
@count = 0
else
# wait if you aren't the nth thread
@cv.wait(@mutex)
end
end
end
end

Notice how we are resetting the ...