Skip to content

Commit 62c2f21

Browse files
committed
Auto-link futures
If a future gets created in an Async context, link it automatically to the runner of that context.
1 parent 30f3389 commit 62c2f21

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

tests/pos/suspend-strawman-2/futures.scala

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,16 @@ object Future:
158158
catch case ex: Exception => Failure(ex))
159159
end RunnableFuture
160160

161-
/** Create a future that asynchronously executes `body` to define
161+
/** Create a future that asynchronously executes `body` that defines
162162
* its result value in a Try or returns failure if an exception was thrown.
163+
* If the future is created in an Async context, it is added to the
164+
* children of that context's runner.
163165
*/
164-
def apply[T](body: Async ?=> T)(using Scheduler): Future[T] = RunnableFuture(body)
166+
def apply[T](body: Async ?=> T)(
167+
using scheduler: Scheduler, environment: Async | Null = null): Future[T] =
168+
val f = RunnableFuture(body)
169+
if environment != null then environment.runner.addChild(f)
170+
f
165171

166172
/** A promise defines a future that is be completed via the
167173
* promise's `complete` method.
@@ -185,16 +191,17 @@ end Future
185191
class Task[+T](val body: Async ?=> T):
186192

187193
/** Start a future computed from the `body` of this task */
188-
def run(using Scheduler): Future[T] = Future(body)
194+
def run(using scheduler: Scheduler, environment: Async | Null = null): Future[T] =
195+
Future(body)
189196

190197
/** Parallel composition of this task with `other` task.
191198
* If both tasks succeed, succeed with their values in a pair. Otherwise,
192199
* fail with the failure that was returned first.
193200
*/
194201
def par[U](other: Task[U]): Task[(T, U)] =
195202
Task: async ?=>
196-
val f1 = Future(this.body).linked
197-
val f2 = Future(other.body).linked
203+
val f1 = Future(this.body)
204+
val f2 = Future(other.body)
198205
async.awaitEither(f1, f2) match
199206
case Left(Success(x1)) => (x1, f2.value)
200207
case Right(Success(x2)) => (f1.value, x2)
@@ -207,8 +214,8 @@ class Task[+T](val body: Async ?=> T):
207214
*/
208215
def alt[U >: T](other: Task[U]): Task[U] =
209216
Task: async ?=>
210-
val f1 = Future(this.body).linked
211-
val f2 = Future(other.body).linked
217+
val f1 = Future(this.body)
218+
val f2 = Future(other.body)
212219
async.awaitEither(f1, f2) match
213220
case Left(Success(x1)) => x1
214221
case Right(Success(x2)) => x2

0 commit comments

Comments
 (0)