Skip to content

Instantly share code, notes, and snippets.

@coderaven
Created January 23, 2013 12:57
Show Gist options
  • Save coderaven/4605249 to your computer and use it in GitHub Desktop.
Save coderaven/4605249 to your computer and use it in GitHub Desktop.
Peterson's Process Control Algorithm Implementation in Ruby
(@flag ||= []) << false << false # Initialize @flag[0] and @flag[1] as false
@shared = 0 and @turn # Initialize @shared variable and declare @turn variable
puts "---------- Peterson's Algorithm Implementation ----------"
puts "A process control algorithm to ensure that only one"
puts "process can be in the critical section at any given time."
puts ""
puts "Project Implemented in Ruby by: Raven G. Duran BSIT 2R5"
puts "---------------------------------------------------------",""
puts "Shared critical variable value: #{@shared}",""
a = Thread.fork do
@flag[0] = true
@turn = 1
while @flag[1] == true and @turn == 1
# Busy wait
puts "A is waiting"
sleep 0.5
end
#Critical Section
puts "Process A has entered the critical section!"
sleep 5 # Simulate that A is doing a task on critical section
@shared += 1
# Leave Critical Section
puts "Process A has leaved the critical section!"
@flag[0] = false
end
b = Thread.fork do
@flag[1] = true
@turn = 2
while @flag[0] == true and @turn == 2
# Busy wait
puts "Process B is waiting. (Process A is currently in the critical section)"
sleep 0.5
end
@shared += 1
puts "Process B has entered the critical section!"
sleep 1 # Simulate that B is doing a task on critical section
# Leave Critical Section
puts "Process B has leaved the critical section!"
sleep 0.5
@flag[1] = false
end
# Sync the threads
a.join
b.join
puts ""
puts "The value of shared critical variable is now: #{@shared}"
puts "","(Press anything to exit)"
gets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment