-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducer-Consumer.rb
More file actions
83 lines (64 loc) · 872 Bytes
/
Producer-Consumer.rb
File metadata and controls
83 lines (64 loc) · 872 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Bank
def initialize
@money = 0
@m = Mutex.new
@cv = ConditionVariable.new
end
def add
@m.synchronize{
while @money >5000
puts "add wait"
@cv.wait(@m)
end
n = (rand*2000).to_i
@money += n
puts "add:#{n} :#{@money}"
@cv.broadcast
}
end
def use
@m.synchronize{
while @money <= 0
puts "use wait"
@cv.wait(@m)
end
n = (rand*(@money)).to_i
@money -= n
puts "use:#{n} :#{@money}"
@cv.broadcast
}
end
end
class Parent
def initialize(bank)
@bank = bank
end
def add
@bank.add
end
end
class Child
def initialize(bank)
@bank = bank
end
def use
@bank.use
end
end
bank = Bank.new
parent = Parent.new(bank)
child = Child.new(bank)
t1 = Thread.new{
loop do
parent.add
sleep(rand(2))
end
}
t2 = Thread.new{
loop do
child.use
sleep(rand(2))
end
}
t1.join
t2.join