Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A celluloid implementation of dining philosophers where the forks are actors too. Could cause deadlock since we wait on forks.
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
left = @left_fork.future.lock
right = @right_fork.future.lock
if left.value && right.value
puts "Philosopher #@name eats..."
sleep(rand())
puts "Philosopher #@name belches"
@left_fork.async.unlock
@right_fork.async.unlock
end
self.think
end
end
class Fork
include Celluloid
attr_accessor :free
def initialize
@free = true
end
def lock
@free = false
true
end
def unlock
@free = true
true
end
end
n = 5
forks = []
(1..n).each do |i|
forks << Fork.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
You can’t perform that action at this time.