by brundolf · 3y ago · 0 comments
But none of that sounds anything like a deadlock, so maybe I'm missing some other aspect here
As an aside: "safe" means a very specific thing in Rust contexts, so even if this is analogous to that (preventing a footgun that could have catastrophic consequences), it might be best to use a different word or at least disambiguate. Otherwise people will argue with you about it :)
There’s no big problem here, just write code and run it. If it is a really big problem it will show up in a profiler (if you care enough about performance to care about this issue, you are using a profiler, right… right?)
No. You can absolutely stall (I'm hesitant to use the phrase deadlock because you're not locking, specifically) an async program. More specifically, you can block all of the available scheduler threads. To see for yourself, spawn a bunch of async tasks in a loop that all increment and print a shared counter and then sleep forever. The counter will stop incrementing at some point. Compare that number to the number of scheduler threads your runtime uses. It should look similar.
I think maybe you're conceptually comparing a single threaded Rust program to an async program, which isn't quite accurate. A "normal" program in my experience has many threads. All of these threads can block. One of them blocking does not inherently slow down the rest of the program. Try the above example but spawn a new thread instead of a new async task during each loop iteration. The number will increment much higher, at least until you've exhausted some system limit on the number of threads a process can have.
Maybe there are fancy async runtimes that dynamically expand their threadpool as the number of blocked tasks increases. But naively they all use a threadpool sized at some multiple of the number of real cores your system has, and so will eventually stall if starved.
In any case, it's not generally async-safe to block any thread, ever (obviously if you could prove that the number of async tasks that block is always less than the number of threads the runtime uses, this doesn't hold, but that's a rather wild assumption). And it's impossible for say a library to know the context in which it's being used, so it's never correct for a library that is to be called in an async context to block. It must always yield.
You're right that in the common case things will just appear to slow down since most things don't block for a long time and eventually continue. But there are gnarly edge cases where the entire program stalls. Hence my comparison to memory safety. In the common case memory corruption and dangling pointers aren't horrible they just sometimes cause spurious errors which most programs can recover from. But every once in awhile they cause really bad problems which programs can't recover. Hence why we care.
For a real world example, imagine a server that processes requests. In the async handler block, for some requests you access the filesystem and the device starts experiencing degraded performance due to media errors and read calls never complete. Should the server stop processing healthchecks because some of the requests are having trouble? The answer is almost certainly no. Instead the server should report in its healthcheck that one of its block devices has an increased error rate and tasks are piling up.
Another case would be one involving locks. If you are dealing with a program that involves many workers/consumers waiting for a producer to produce a value and the workers use a blocking api to wait on a semaphore before reading a next value from memory and continuing, the program will almost certainly deadlock not because of a logic error leading to an imbalanced semaphore but instead because the async runtime will stall and the producer will never produce a value. If instead the tasks yield as they should, the program would progress normally.
Ok yeah, I think this was the disconnect
> spawn a bunch of async tasks in a loop that all increment and print a shared counter and then sleep forever
My instinct is "duh, of course sleeping/looping forever will prevent progress". I can see how in a multithreaded program it might not (if it's written a certain way), but that feels like the exception, not a norm/intuitive assumption. Of course these things are highly subjective
In my view it's an exaggeration to call functions that might block for a long time "not async safe". Especially since it's in no way worse than the single-threaded case (are they also "not sync safe"?). I think for most people the blocking behavior will be obvious/intuitive, even if it has the potential to cause undesirable behavior (just like any program logic could)
It may be a matter of changing expectations- async programming is mainly about interlacing tasks on a thread, not multithreading; it's useful even when there's only one single thread available. It just so happens that you can also spread it across multiple threads, but I don't think it should be expected to live up to every expectation we might have around fully, manually multi-threaded logic
I've seen this happen in non-contrived scenarios in the real world. It's not common, I'll give you that, but definitely not contrived.
Edit: I disagree about expectations. Async programs should absolutely work correctly in all scenarios that aren't programmer/logic errors. In my example(s) the solution is not "rewrite the program the program is wrong". The solution is "use the correct async-aware function at the call site and the issue goes away". The fact that Rust is being used to write web servers means that async/await is up to the task of handling real world highly parallel programs. You just have to be careful to avoid some nuanced traps, which the Rust compiler currently doesn't assist you with. It totally should!
Consider a function that isn't doing IO, but it takes a long, potentially variable amount of time (i.e. it "blocks" as long as a file system request might block)
Is it even possible for that function to be "async-safe"? If you have it spin off a separate async task and yield to the original one, that's still filling up your thread pool. The only full solution then would be to manually create a separate thread outside of the async workers (until the OS hits the thread limit, of course)
This too is a little contrived, but I don't see a hard distinction between this and the IO case
At some point: the computer has finite resources, and those can get overloaded. There's something here around how async runtimes might not be making full use of the machine, which is an interesting thread (no pun intended) to pull on. But I don't think we can expect the language (at least as currently designed) to fully prevent this class of problem. And I also don't think the standard library should orient itself around async use-cases, which are still a minority of Rust uses, especially for the sake of an edge-case like this one
"Not async safe" is a loaded term here that means "not complying with requirements of being a good citizen in the entire forest of async workers". As another poster said: it's expected most workers to return in 0.1 - 1.0 ms. After that the guarantees of async start to fall apart.
It's the same with Erlang's BEAM btw: it has an amazing scheduling primitives and you can literally spawn 50k green threads and you'd barely see a blip of lag anywhere BUT that's because the scheduler is preemptive and aggressively switches off a worker if it hasn't yielded in a while (this is not 100% the truth, I am simplifying it here). But if you start calling native functions that don't respond in 1ms or less, the scheduler is starting to struggle and you do start seeing lags that you normally never would.
So yeah, "not async safe" here means more or less "not being a good citizen".
No abstraction is free. Until we have something like the BEAM on a hardware level and anything and everything is preempted without you ever having a say on it, then such async runtime if-s and but-s will keep existing. It's a fundamental limitation of our hardware and OS-es.
I’d call that an unforced programmer error.