zlacker

[parent] [thread] 3 comments
1. doakes+(OP)[view] [source] 2024-01-20 02:57:30
I guess I'm just confused that it's labeled async (and does async work) but is actually blocking when invoked (or at least doesn't return until await finishes).

If I'm awaiting on two different results, I have to invoke them in parallel somehow, right? What is that mechanism and why doesn't that already provide asynchrony? Like, if the method was sync, couldn't I still run it async somehow?

replies(3): >>mplanc+e3 >>Too+th >>SkiFir+8r
2. mplanc+e3[view] [source] 2024-01-20 03:35:07
>>doakes+(OP)
This is sort of the core of the whole idea of concurrency. There are lots of good explanations online if you search for “concurrency vs parallelism.”

The gist is that while you await the result of an async function, you yield to the executor, which is then free to work on other tasks until whatever the await is waiting for has completed.

The group of tasks being managed by the executor is all different async functions, which all yield to the executor at various times when they are waiting for some external resource in order to make forward progress, to allow others to make progress in the meantime.

This is why people say it’s good for IO-bound workloads, which spend the majority of their time waiting for external systems (the disk, the network, etc)

3. Too+th[view] [source] 2024-01-20 06:44:43
>>doakes+(OP)
You might be awaiting for only one result, but the one calling you may be awaiting both you and 100 other things that you are not aware of.
4. SkiFir+8r[view] [source] 2024-01-20 09:17:40
>>doakes+(OP)
> I guess I'm just confused that it's labeled async (and does async work) but is actually blocking when invoked (or at least doesn't return until await finishes).

From the point of view of the `async` block/function, it is blocking, but from the point of view of the thread executing that `async` block/function it is not.

> If I'm awaiting on two different results, I have to invoke them in parallel somehow, right?

No, the whole point of `async` is having concurrency (i.e. multiple tasks running and interleaving) without necessarily using parallelism for it. Take a look at the `join` macro in the `futures` crate for example, it allows you to `.await` two futures while allowing both of them to make progress (two successive `.await`s would force the first one to end before the second one can start) and without spawning dedicated threads for them.

[go to top]