diff --git a/lib/peach.rb b/lib/peach.rb index c1e8aa9..0271fed 100644 --- a/lib/peach.rb +++ b/lib/peach.rb @@ -52,3 +52,27 @@ def pselect(pool = nil, &b) result end end + +class File + def _peach_run(pool = nil, &b) + pool ||= $peach_default_threads || count + pool = 1 unless pool >= 1 + div = (count/pool).to_i # should already be integer + div = 1 unless div >= 1 # each thread better do something! + + threads = [] + each_slice(div).with_index do |slice, idx| + threads << Thread.new(slice) do |thread_slice| + yield thread_slice, idx, div + end + end + threads.each{|t| t.join } + self + end + + def peach_line(pool = nil, &b) + _peach_run(pool) do |thread_slice, idx, div| + thread_slice.each{|elt| yield elt} + end + end +end diff --git a/test/data.txt b/test/data.txt new file mode 100644 index 0000000..469c856 --- /dev/null +++ b/test/data.txt @@ -0,0 +1,16 @@ +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 diff --git a/test/peach_test.rb b/test/peach_test.rb index 4a9c695..583c8c9 100644 --- a/test/peach_test.rb +++ b/test/peach_test.rb @@ -43,4 +43,18 @@ class PeachTest < Test::Unit::TestCase end end + [:peach_line].each do |f| + context "#{f}" do + normal_f = f.to_s[1..-1].to_sym + + setup do + @data = File.open(File.join(File.dirname(__FILE__), 'data.txt'), 'r') + @block = lambda{|i| i.to_i**2} + end + should "return the same result as #{normal_f}" do + assert_equal @data.send(normal_f, &@block), + @data.send(f, 100, &@block) + end + end + end end