ELF: On reduce, hop to target EventLoop before doing operation (#1070)

Motivation:

Folds often involves chaining multiple futures together. It's
beneficial if you're already on the target EventLoop as it might
vastly reduce the amount of EventLoop hops.

Modifications:

Execute onto the target EventLoop before doing the folds.

Result:

Fixes #1054
This commit is contained in:
Johannes Weiss authored and GitHub committed 2019-07-17 13:54:25 +01:00
1 parent 6b20fa5ce8
commit fb03f947a5
1 file changed
+20 -8
+20 -8
View File
@@ -919,16 +919,28 @@ extension EventLoopFuture {
@inlinable
public func fold<OtherValue>(_ futures: [EventLoopFuture<OtherValue>],
with combiningFunction: @escaping (Value, OtherValue) -> EventLoopFuture<Value>) -> EventLoopFuture<Value> {
let body = futures.reduce(self) { (f1: EventLoopFuture<Value>, f2: EventLoopFuture<OtherValue>) -> EventLoopFuture<Value> in
let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture<Value> in
let (f1Value, f2Value) = args
self.eventLoop.assertInEventLoop()
return combiningFunction(f1Value, f2Value)
func fold0() -> EventLoopFuture<Value> {
let body = futures.reduce(self) { (f1: EventLoopFuture<Value>, f2: EventLoopFuture<OtherValue>) -> EventLoopFuture<Value> in
let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture<Value> in
let (f1Value, f2Value) = args
self.eventLoop.assertInEventLoop()
return combiningFunction(f1Value, f2Value)
}
assert(newFuture.eventLoop === self.eventLoop)
return newFuture
}
assert(newFuture.eventLoop === self.eventLoop)
return newFuture
return body
}
if self.eventLoop.inEventLoop {
return fold0()
} else {
let promise = self.eventLoop.makePromise(of: Value.self)
self.eventLoop.execute {
fold0().cascade(to: promise)
}
return promise.futureResult
}
return body
}
}