3 ms·
I have never used async/await and cant really understand it. Is it like coroutines in lua? It seems very similar. But I guess its not limited to one thread like
by jdance 7y ago
I have never used async/await and cant really understand it. Is it like coroutines in lua? It seems very similar. But I guess its not limited to one thread like lua? Whats makes it better then threaded IO? Losing the overhead of threads?
I like coroutines but thats mostly because they are not threads, they only switch execution on yield, and that makes them easy to reason about :)
- uryga 7y ago> Is it like coroutines in lua? idk about Lua, but afaik python's async is pretty much implemented on top of coroutines ("generators"). `await` is basically `yield` > I like coroutines but thats mostly because they are not threads, they only switch execution on yield, and that makes them easy to reason about :) pretty sure i've heard the same thing said about async io!
- jdance 7y agoI guess the thing that puzzles me is that if they are run threaded (concurrently) they seem just as hard to reason about as threaded IO to me. And that would leave the motivation to be performance gains by being able to reduce the amount of threads I guess (And that it is cool of course :)
- uryga 7y agothe coroutines are run sequentially by an "event loop"/"coroutine runner" that wakes them up and lets them run for a bit when appropriate, kind of like an OS's scheduler (on a single core machine). if the runner is the OS, `await foo(..)` is kind of like a syscall, where the coroutine is suspended and control is handed back to the runner to do whatever is requested. i guess the difference from normal threads (preemptive multitasking) is that you explicitly mark your "yield points" – places where your code gives control back to the runner – with `await` (cooperative multitasking). some believe that this makes async stuff easier to reason about, since in theory you can see the points where stuff might happen concurrently honestly i'm out of my depth re: async IO, haven't used it all that much :/ but if you're comfortable with python and want to dig into the mechanism of async/await, i really recommend this article: https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/ https://snarky.ca/how-the-heck-does-async-await-work-in-pyth... it's long, but i found it very helpful – it actually explains how it all works without handwaviness. at the end the author implements a toy "event loop" that can run a few timers concurrently, which really made it click for me!