-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathphilosopher.rb
More file actions
51 lines (42 loc) · 850 Bytes
/
philosopher.rb
File metadata and controls
51 lines (42 loc) · 850 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Philosopher < Thread
attr_accessor :name, :left_chopstick, :right_chopstick, :finished
def initialize args = {}
args.each_pair { |attribute, value| self.__send__ "#{attribute}=", value }
@finished = false
# puts "#{name} (#{left_chopstick.id},#{right_chopstick.id})"
super { start }
end
def eat
left_chopstick.synchronize {
right_chopstick.synchronize {
emote 'is eating'
ponder
}
}
end
def think
emote 'is thinking'
ponder
end
def ponder min=4, max=8
return if @finished
sleep rand min..max
end
def emote str
$g_lock.synchronize {
puts "#{name} #{str}"
}
end
def start
sleep 1
while !@finished
think
break if @finished
eat
end
emote 'is finished'
end
def stop
@finished = true
end
end