Skip to content

Instantly share code, notes, and snippets.

@lmmendes
Created May 23, 2017 13:04
Show Gist options
  • Save lmmendes/02ba040f60405d0f417592a6a2b3fc16 to your computer and use it in GitHub Desktop.
Save lmmendes/02ba040f60405d0f417592a6a2b3fc16 to your computer and use it in GitHub Desktop.
tinkering around with concurrent notions
module Parallel
def cpu_cores
2
end
def parallel_each(&block)
t = []
each_slice(cpu_cores).each do |items|
t << Thread.new do
items.each do |item|
yield item
end
end
end
t.collect(&:join)
end
def parallel_sum
t = []
each_slice(cpu_cores).each do |items|
puts "Thread.."
t << Thread.new do
Thread.current[:output] = items.inject(&:+)
end
end
output = 0
t.each do |thread|
thread.join
output += thread[:output]
end
output
end
end
class Array
prepend Parallel
end
Array.new([1,2,3,4,5]).parallel_each do |a|
puts "#{a}"
sleep (1..5).to_a.sample
end
puts Array.new([1,2,3,4,5]).parallel_sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment