Skip to content

Commit 2e8027a

Browse files
davishmcclurgpitr-ch
authored andcommitted
Allow setting executor for zipped promises
The use case for this is a little strange, since you can set the executors for the zipped promises when they're created instead. In my case, it would make it easier to run a number of immediately executed promises on a pool: ``` p1 = Concurrent::Promise.new(executor: :immediate) { ... } p2 = Concurrent::Promise.new(executor: :immediate) { ... } ... Concurrent::Promise.zip(p1, p2, executor: SOME_THREAD_POOL).then { ... } ```
1 parent 641436c commit 2e8027a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

lib/concurrent/promise.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,9 @@ def flat_map(&block)
387387
#
388388
# @return [Promise<Array>]
389389
def self.zip(*promises)
390-
zero = Promise.new(executor: ImmediateExecutor.new) { [] }
390+
opts = promises.last.is_a?(::Hash) ? promises.pop : {}
391+
opts[:executor] ||= ImmediateExecutor.new
392+
zero = Promise.new(opts) { [] }
391393

392394
promises.reduce(zero) do |p1, p2|
393395
p1.flat_map do |results|

spec/concurrent/promise_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,14 @@ def get_ivar_from_args(opts)
363363
expect(composite).to be_unscheduled
364364
end
365365

366+
it 'allows setting executor for Promise chain' do
367+
new_executor = Concurrent::SingleThreadExecutor.new
368+
promise = promise1.zip(promise2, promise3, executor: new_executor)
369+
370+
promise = promise.instance_variable_get(:@parent) until promise.send(:root?)
371+
expect(promise.instance_variable_get(:@executor)).to be(new_executor)
372+
end
373+
366374
it 'yields the results as an array' do
367375
composite = promise1.zip(promise2, promise3).execute.wait
368376

@@ -387,6 +395,14 @@ def get_ivar_from_args(opts)
387395
expect(composite).to be_unscheduled
388396
end
389397

398+
it 'allows setting executor for Promise chain' do
399+
new_executor = Concurrent::SingleThreadExecutor.new
400+
promise = Promise.zip(promise1, promise2, promise3, executor: new_executor)
401+
402+
promise = promise.instance_variable_get(:@parent) until promise.send(:root?)
403+
expect(promise.instance_variable_get(:@executor)).to be(new_executor)
404+
end
405+
390406
it 'yields the results as an array' do
391407
composite = Promise.zip(promise1, promise2, promise3).execute.wait
392408

0 commit comments

Comments
 (0)