Skip to content

Instantly share code, notes, and snippets.

@egonSchiele
Created May 13, 2013 01:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egonSchiele/5565713 to your computer and use it in GitHub Desktop.
Save egonSchiele/5565713 to your computer and use it in GitHub Desktop.
Another implementation of the dining philosophers in Ruby using Celluloid. This time the forks are mutexes and we don't block to acquire them.
require 'rubygems'
require 'celluloid'
class Philosopher
include Celluloid
def initialize(name, left_fork, right_fork)
@name = name
@left_fork = left_fork
@right_fork = right_fork
self.think
end
def think
puts "Philosopher #@name is thinking..."
sleep(rand())
puts "Philosopher #@name is hungry..."
self.async.dine
end
def dine
if @left_fork.try_lock && @right_fork.try_lock
puts "Philosopher #@name eats..."
sleep(rand())
puts "Philosopher #@name belches"
@left_fork.unlock
@right_fork.unlock
else
puts "Philosopher #@name couldn't get a fork"
end
self.think
end
end
n = 5
forks = []
(1..n).each do |i|
forks << Mutex.new
end
(1..n).each do |i|
left_fork = forks[i-1]
right_fork = i < n ? forks[i] : forks[0]
Philosopher.new(i, left_fork, right_fork)
end
sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment