Hacker News new | ask | show | jobs
by spacechild1 344 days ago
I was just going to mention ASIO.

> and that seemed complex to use

Actually. I found it pretty straightforward. I switched from callbacks to coroutines un my personal project and it is a massive win! Now I can write simple loops instead of nested callbacks. Also, most state can now stay in local variables.

1 comments

There is another way to write code which lets you write simple loops and isn’t coroutines. Blocking code.
But the great thing about async (at least it's the killer feature for me) is the really top notch support for cancellation. You can also typically create and join async tasks more easily than spawning and joining threads.
Sure, but then you need one thread per socket, which has its own set of problems (most notably, the need for thread synchronization). I definitely prefer async + coroutines over blocking + thread-per-socket.
Java's new philosophy (in "Loom" - in production OpenJDK now) seems to be virtual threads that are cheap and can therefore be plentiful compared to native threads. This allows you to write the code in the old way without programmer-visible async.
That sounds interesting, I'll take a look! (although not using native threads is almost never about perf)
Ok, but virtual threads still need thread synchronization.
which isn't a problem unless you are abusing threads.

If you avoid synchronization, like javascript then you also don't get pre-emption or parallelism.

> which isn't a problem unless you are abusing threads.

Well, some people would call this a problem (or downside). Many real-world programs need to access shared state or exchange data between client. This is significantly less error prone if everything happens on a single thread.

> If you avoid synchronization, like javascript then you also don't get pre-emption or parallelism.

When we are talking about networking, most of the time is spent waiting for I/O. We need concurrency, but there's typically no need for actual CPU level parallelism.

I'm not saying that we shouldn't use threads at all - on the contrary! -, but we should use them where they make sense. In some cases we can't even avoid it (e.g. audio).

A typical modern desktop application, for example, would have the UI on the main thread, all the networking on a network thread, audio on an audio thread, expensive calculations on a worker thread (pool), etc.

IMO it just doesn't make sense to complicate things by having one thread per socket when all the networking can easily be served by a single thread.