Skip to content

Commit a3e7448

Browse files
author
Fredrik Johansson
committed
Only one queue
1 parent 673cf3d commit a3e7448

File tree

2 files changed

+16
-17
lines changed

2 files changed

+16
-17
lines changed

lib/forkoff.rb

+6-17
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def forkoff options = {}, &block
137137
options = { 'processes' => Integer(options) } unless Hash === options
138138
n = Integer( options['processes'] || options[:processes] || Forkoff.default['processes'] )
139139
strategy = options['strategy'] || options[:strategy] || 'pipe'
140-
qs = Array.new(n){ SizedQueue.new 1 }
140+
qs = SizedQueue.new 1 # One queue
141141
results = Array.new(n){ [] }
142142

143143
#
@@ -151,7 +151,7 @@ def forkoff options = {}, &block
151151
Thread.current.abort_on_exception = true
152152

153153
loop do
154-
value = qs[i].pop
154+
value = qs.pop
155155
break if value == Forkoff.done
156156
args, index = value
157157

@@ -175,23 +175,12 @@ def forkoff options = {}, &block
175175
end
176176

177177
#
178-
# producers
178+
# one producer
179179
#
180-
producers = []
181-
182-
n.times do |i|
183-
thread = Thread.new do
184-
Thread.current.abort_on_exception = true
185-
each_with_index do |args, j|
186-
every_nth = j.modulo(n) == i
187-
next unless every_nth
188-
qs[ j.modulo(n) ].push( [args, j] )
189-
end
190-
qs[ i ].push( Forkoff.done )
191-
end
192-
193-
producers << thread
180+
each_with_index do |args, j|
181+
qs.push( [args, j] )
194182
end
183+
n.times do qs.push( Forkoff.done ) end
195184

196185
#
197186
# wait for all consumers to complete

test/forkoff.rb

+10
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,14 @@ def test_0020
3838
end
3939
end
4040

41+
# in case of different execution times for different processes
42+
#
43+
def test_0030
44+
t0 = Time.now
45+
(0...4).forkoff(2) do |i|
46+
sleep i.modulo(2)
47+
end
48+
assert (Time.now - t0) < 2
49+
end
50+
4151
end

0 commit comments

Comments
 (0)