Created
May 23, 2017 13:04
-
-
Save lmmendes/02ba040f60405d0f417592a6a2b3fc16 to your computer and use it in GitHub Desktop.
tinkering around with concurrent notions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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