-
Notifications
You must be signed in to change notification settings - Fork 0
/
threading_queue_pooled.rb
71 lines (60 loc) · 1.31 KB
/
threading_queue_pooled.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
class ThreadPool
def initialize(num_threads)
@threads = Array.new
@lock = Mutex.new
@resource = ConditionVariable.new
num_threads.times.each_with_index do |i|
@threads << Thread.new do
until @finished do
task = nil
@lock.synchronize do
@resource.wait(@lock)
task = @task_queue.pop
end
puts "T#{i} begins #{task.id}"
task_data = task.call
sleep rand() * 10
puts "T#{i} completes #{task.id}: #{task_data}"
end
end
end
@task_queue = Queue.new
@finished = false
end
def push(task)
@task_queue.push task
end
def join_all # does not work correctly
@threads.each {|thread| thread.join}
end
def kill_all
@finished = true
@threads.each {|thread| thread.kill}
end
attr_accessor :finished, :resource
attr_reader :task_queue #debug
end
class Task
def initialize(id, &block)
@id = id
@block = block
end
def call
@block.call
end
def to_s
"#<Task: @id=#{@id}"
end
attr_reader :id
end
Thread.abort_on_exception = true
tp = ThreadPool.new 4
i = 0
until i > 20 do
tp.push Task.new(i) {"..."}
puts "adding #{i} to queue #{tp.task_queue.inspect}"
tp.resource.signal
i+=1
sleep rand()
end
#tp.join_all