Created
May 13, 2013 01:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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