logoalt Hacker News

ameliustoday at 3:47 PM5 repliesview on HN

Don't use async but use threads instead. Threading treats the CPU as a resource, which it is! Whereas async simply locks the CPU, which can deplete the system for longer computations.

If you hate garbage collection pauses (which most Rust users do) then don't use async.


Replies

himata4113today at 4:03 PM

You use async to preserve system resources. For example you can easily exhaust the host with ~20k connections running a thread-per-connection schema where each thread simply waits for epoll event, async prevents this by having a threadpool of ~16 threads that handle all the connections instead of polling the scheduler wakes it up, asks "do you haev work to do" if not continues to next task. (This heavily varied by the async runtime implementation, each async runtime can and will act differently to maximize efficiency over throughput)

Salgattoday at 5:48 PM

The whole point of async/await (besides allowing synchronous style code instead of callbacks) is that it lets you yield the thread efficiently back to the executor (OS threads have a massive overhead in comparison). And if you're doing something that blocks the thread instead of yielding it, you can choose between either spawn_blocking or a thread pool.

inigyoutoday at 4:49 PM

They are two different models and sometimes one is better than the other. Async tends to win for IO-bound code (due to using less memory for each blocked coroutine) and threads for CPU-bound code.

LtWorftoday at 5:51 PM

The problem with all these async things is that people don't understand what's actually happening.

It's just doing a loop and a call to poll(), that's it.

It's way way way less expensive than using threads. Of course you must give control to your main loop every once in a while, so if you have a long computation you either create a thread or split it and return control to your main loop.

It's how all GUI programming has always been done.

toprerulestoday at 3:57 PM

Your confusing concurrency with parallelism. Async allows one core to switch between many threads of execution that can do work and not stop one thread of execution because it needs to wait for a resource. It's beneficial to use async if you're application is I/O heavy even if it's single threaded.

> Whereas async simply locks the CPUWhereas async simply locks the CPU

This is also completely nonsense, context switching behavior is OS dependent and your average general purpose kernel is not cooperative. You will run for your allotted quanta or reschedule when you run out of coroutines that can execute without waiting for resources.