Created
May 13, 2013 01:50
-
-
Save egonSchiele/5565704 to your computer and use it in GitHub Desktop.
A celluloid implementation of dining philosophers where the forks are actors too. Could cause deadlock since we wait on forks.
This file contains hidden or 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 | |
| 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