Avoid stack overflow error with Future.after #29
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is an attempt at solving #28, without introducing the need to protecting the compound nil future with locks. It should be noted that I have not (yet) performed any extensive tests with respect to the thread safety of the solution.
With a long list of resolved futures, the previous implementation caused a stack-overflow exception, as each call to await_next happened within the previous call (synchronously).
This changes the behavior to loop over futures instead of using recursion while on_complete dispatches synchronously in the same thread. To avoid code duplication we always dispatch in the terminating cases,
even if it introduces an extra stack frame. The looping condition protects against cases where a future would be resolved at a later point by the calling thread (which is what the tests do), and the last part of the condition protects against dispatching in other threads.
While the algorithm looks like a loop that adds multiple concurrent on_complete listeners, the intention is in fact still to only ever have one concurrent listener, making sure that the combined nil future is only ever accessed from one thread at a time (without using locks).