[swift-evolution] Contextualizing async coroutines

Joe Groff jgroff at apple.com
Wed Sep 6 18:28:28 CDT 2017


> On Sep 2, 2017, at 1:57 AM, Brent Royal-Gordon <brent at architechies.com> wrote:
> 
>> On Aug 31, 2017, at 11:35 AM, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> # Coroutine context
>> 
>> # `onResume` hooks
> 
> `onResume` hooks seem like a really good way to, essentially, allow arbitrary concurrency primitives to be passed into `async` functions. My main question is, if we have it, why do we need coroutine contexts? It seems to me that anything the coroutine might do with the context could either be passed into its parameters, or encapsulated in its `onResume` hook.

To be clear, I'm *not* claiming we necessarily need both. I'm exploring two options here to the problem of "how can I ensure a coroutine's execution is consistently associated with a specific context", from different directions. Context values allow information about the desired execution context to be pushed through the actual execution, which is the most efficient thing if all the code is cooperating, although it's still up to the yielding operation to use that information. 'onResume' can pull a resumed coroutine back into whatever context it expects to run in, which imposes some fundamental overhead in the form of "queue-hopping" in the GCD model or other rescheduling, but on the other hand can provide stronger guarantees about where execution is happening even without perfect cooperation across all code.

-Joe

>> and also prevents writing APIs that intentionally change context across an `await`, like a theoretical "goToMainThread()" function
> 
> You say that like it's a bad thing. :^)
> 
> (Seriously, I feel like that makes it *way* too easy to jump to another thread in the middle of a function using what looks like an ordinary line of code. A `let result = await someQueue.async { … }` syntax is a lot clearer that you're hopping to another thread and about what code will run on it, but can get around our current "pyramid of doom" problem. If the async syntax guarantees that the code before and after the `await` runs in the same "environment"—whatever environment is set up by the onResume hook—then that makes async functions much safer and easier for programmers to reason about, while only restricting their power slightly.)
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 



More information about the swift-evolution mailing list