-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.rb
85 lines (67 loc) · 1.03 KB
/
Worker.rb
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
81
require "singleton"
class Worker
def initialize(request)
@request = request
end
def work
num = @request.give_task
puts"#{num}処理終了"
end
end
class Task
def initialize(request)
@request = request
@num = 0.to_i
end
def make_task
@num += 1
data = "仕事"[email protected]_s
@request.get_task(data)
puts "#{data}追加"
end
end
class Request
include Singleton
def initialize
@queue = Array.new
@m = Mutex.new
@cv = ConditionVariable.new
end
def get_task(data)
@m.synchronize{
while @queue.size >10
puts "追加待機"
@cv.wait(@m)
end
@queue.push(data)
@cv.broadcast
}
end
def give_task
@m.synchronize{
while @queue.empty?
puts("処理待機")
@cv.wait(@m)
end
dt = @queue.shift
@cv.broadcast
return dt
}
end
end
worker = Worker.new(Request.instance)
task = Task.new(Request.instance)
t1 = Thread.new{
100.times do
task.make_task
sleep rand(2)
end
}
t2 = Thread.new{
100.times do
worker.work
sleep rand(2)
end
}
t1.join
t2.join