Skip to content

Instantly share code, notes, and snippets.

@egonSchiele
Last active October 30, 2022 06:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egonSchiele/5565009 to your computer and use it in GitHub Desktop.
Save egonSchiele/5565009 to your computer and use it in GitHub Desktop.
The dining philosophers problem in Ruby, solved using the resource hierarchy solution
require 'thread'
class Ron
def initialize(name, left_fork, right_fork)
@name = name
@left_fork = left_fork
@right_fork = right_fork
while true
think
dine
end
end
def think
puts "Ron #@name is thinking..."
sleep(rand())
puts "Ron #@name is hungry..."
end
def dine
while true
@left_fork.lock
puts "Ron #@name has one fork..."
if @right_fork.try_lock
break
else
puts "Ron #@name cannot pickup second fork"
@left_fork.unlock
end
end
puts "Ron #@name has the second fork!"
puts "Ron #@name eats..."
sleep(rand())
puts "Ron #@name belches"
@left_fork.unlock
@right_fork.unlock
end
end
n = 5
forks = []
(1..n).each do |i|
forks << Mutex.new
end
threads = []
(1..n).each do |i|
threads << Thread.new do
if i < n
left_fork = forks[i]
right_fork = forks[i+1]
else
# special case for philosopher #5 because he gets forks #5 and #1
# and the left fork is always the lower id because that's the one we try first.
left_fork = forks[0]
right_fork = forks[n]
end
Ron.new(i, left_fork, right_fork)
end
end
threads.each {|thread| thread.join}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment