Skip to content

Instantly share code, notes, and snippets.

@midhunkrishna
Last active December 1, 2017 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save midhunkrishna/840d162d9712c11463196dd1f823592a to your computer and use it in GitHub Desktop.
Save midhunkrishna/840d162d9712c11463196dd1f823592a to your computer and use it in GitHub Desktop.
module ConcurrentExecutor
class Error < StandardError
def initialize(exceptions)
@exceptions = exceptions
super
end
def message
@exceptions.map { | e | e.message }.join "\n"
end
def backtrace
trace = @exceptions.map { |e| e.backtrace }.join("\n")
"ConcurrentExecutor::Error START\n #{trace} \nEND \n"
end
end
class Promise
def initialize(pool: nil)
@pool = pool || Concurrent::FixedThreadPool.new(20)
@exceptions = Concurrent::Array.new
end
# Sample Usage
# executor = ConcurrentExecutor::Promise.new(pool: pool)
# executor.execute(carriers) do | carrier |
# ...
# end
#
# values = executor.resolve
def execute array, &block
@futures = array.map do | element |
Concurrent::Promise.execute({ executor: @pool }) do
yield(element)
end.rescue do | exception |
@exceptions << exception
end
end
self
end
def resolve
values = @futures.map(&:value)
if @exceptions.length > 0
raise ConcurrentExecutor::Error.new(@exceptions)
end
values
end
end
end
executor = ConcurrentExecutor::Promise.new.execute(carriers) do |carrier|
# ...
end
values = []
begin
values = executor.resolve
rescue ConcurrentExecutor::Error => e
raise e
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment