From fb03f947a54b3562d3827d17cfc1d4e7cf75868f Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Wed, 17 Jul 2019 13:54:25 +0100 Subject: [PATCH] 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 --- Sources/NIO/EventLoopFuture.swift | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/Sources/NIO/EventLoopFuture.swift b/Sources/NIO/EventLoopFuture.swift index 0fdc64eae..3aea2cda0 100644 --- a/Sources/NIO/EventLoopFuture.swift +++ b/Sources/NIO/EventLoopFuture.swift @@ -919,16 +919,28 @@ extension EventLoopFuture { @inlinable public func fold(_ futures: [EventLoopFuture], with combiningFunction: @escaping (Value, OtherValue) -> EventLoopFuture) -> EventLoopFuture { - let body = futures.reduce(self) { (f1: EventLoopFuture, f2: EventLoopFuture) -> EventLoopFuture in - let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture in - let (f1Value, f2Value) = args - self.eventLoop.assertInEventLoop() - return combiningFunction(f1Value, f2Value) + func fold0() -> EventLoopFuture { + let body = futures.reduce(self) { (f1: EventLoopFuture, f2: EventLoopFuture) -> EventLoopFuture in + let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture 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 } }