zlacker

[return to "The bane of my existence: Supporting both async and sync code in Rust"]
1. doakes+nq[view] [source] 2024-01-20 00:52:30
>>lukast+(OP)
What's the advantage of async if you immediately call await?
◧◩
2. sodali+sr[view] [source] 2024-01-20 01:03:44
>>doakes+nq
If you're I/O bound, it allows for easy and efficient utilization of resources by enabling other tasks to run while waiting for I/O.

I'll give you a real world example. I wrote some code that listened to a websockets URL from thousands of Reddit posts - specifically, the one that sends new messages on new comments - so I could see a stream of Reddit comments for any given sub.

Implemented it using Tungstenite (synchronous) and it created thousands of threads to listen, and used enormous chunks of memory (several GB) for the stack space + memory reading for every single WS stream.

Implemented it using Tokio_tungstenite, the async alternative, and it used a handful of MB of memory and barely any CPU to listen to thousands of WS servers.

◧◩◪
3. doakes+Zt[view] [source] 2024-01-20 01:27:12
>>sodali+sr
But at what point are you calling await?

If I were using the author's library, I would call `.some_endpoint(...)` and that would return a `SpotifyResult<String>`, so I'm struggling to understand why `some_endpoint` is async. I could see if two different threads were calling `some_endpoint` then awaiting would allow them to both use resources, but if you're running two threads, doesn't that already accomplish the same thing? I'm pretty naive to concurrency.

◧◩◪◨
4. roywig+0w[view] [source] 2024-01-20 01:46:05
>>doakes+Zt
If you are only ever doing one thing at a time, then async doesn't do you any good, which is why people like to use sync libraries when they can't make use of it, and why libraries might want to provide a sync and an async version.

Async is useful when you want to have a bunch of things happening (approximately) "at the same time" on a single thread.

With async you can await on two different SpotifyResults at the same time without multithreading. When each one is ready, the runtime will execute the remainder of the function that was awaiting. This means the actual HTTP requests can be in flight at the same time.

◧◩◪◨⬒
5. doakes+jC[view] [source] 2024-01-20 02:57:30
>>roywig+0w
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?

[go to top]