226 points · by tannhaeuser · 5y ago · 295 comments
Most of the difficulty comes from Rust not having a GC yet wishing to keep track of object lifetimes precisely: a GC'ed language needs no distinction between an ordinary function pointer and a closure that captures the environment. But Rust being a low-level systems language chose not to have a GC.
Another popular language also doesn't have GC, makes distinctions between ordinary function pointers and closures, and its closures are unnameable types; that language is C++. But instead of using template for closures everywhere (like the STL), you can optionally use std::function<R(Arg)>, a type-erased closure type, which would in principle be similar to Box<dyn Fn(Arg) -> R> in Rust. But such a type doesn't really mention the lifetimes of whatever it captures, so in practice it doesn't work well in Rust (though std::function works well in C++ because the C++ doesn't care about lifetimes).
With that in mind, I see this article as not understanding the goals and tradeoffs of Rust. The author would be happier writing in a higher-level language than Rust.
If anything, I think the issue with Rust's async is that it tries to be too high level.
In my experience with async rust, most of the difficulty comes from "spooky errors at a distance". I.e, you're writing some code which feels completely normal, and then suddenly you are hit with a large, obtuse error message about types and traits you didn't even know you were working with. The reason being, something went wrong with all the inference involved in implicitly wrapping everything in futures. And often it's not even related to the line of code you just wrote.
So in these cases, I think the issue is that rust tries very hard to wrap async in a very smooth, sugared syntax. It works fine in a lot of cases, but due to the precise nature of Rust, there are a cases where it doesn't work. And because the system relies on a lot of magic inference, the programmer has to hold a lot of assumptions and rules in their mind to work effectively with async.
I am not an expert, but from my experience it feels like async rust was a bit rushed. It should have been introduced as a more explicit syntax first, with sugar on top once the guard rails had better been figured out through experimentation.
That is under the assumption that future-based async in rust is a good idea at all. Rust's ownership model becomes intuitive very quickly in the single-threaded case, but at times it feels like a square peg in a round hole where async is concerned.
Go was not designed around the idea of "async". Its goroutine approach was inspired by https://en.wikipedia.org/wiki/Communicating_sequential_proce..., a nice theoretical model for concurrency.
After a lot of wrassling with it, once I realized that it was a very shallow abstraction over what the hardware is actually doing, everything clicked.
Each have their own usage, and no, a multi-threaded program is not the same as an asynchronous one. For example, using threads and channels instead of async/await is not a design flaw if your workload is mostly about large, blocking computations on a read-only shared state with no I/O. In that situation, lifetime and closures will not pose any issue and won't get in the way because you're not mutating anything and communicate with owned messages.
The async ecosystem is evolving and will be better tomorrow than it is today. Saying that Rust programming as a whole is a mess because async/await is harder to use than necessary, is short-sighted. It's like saying you don't like apples, but you only chewed on the branch of the tree.
they don't quite mix. so you need to be aware of which one you're (implicitly using), and you may need library functions for both colors.
you have to admit this adds some additional mental overhead. but what got me when trying to understand the language was just that there _was_ such a division. I actually tried to apply the lifetime model to asynch objects.
Mmh, I'm not sure I would agree with that. I've been using Arc & Rc for both async and non-async code, and even in single-threaded code. It's less about what flavor of concurrency you're using, than what program you're writing.
Arcs and references can coexist and are useful for different reasons. It would be a tragic loss for me if the language was (re-)adopting garbage collection or reference counting globally -even optionally. They are made to go along one another.
Edit: for example, tree-like or graph-like structures can use Arc and Weak [see arc documentation] in single-threaded code to enjoy reference-counted, cyclic, heap allocations in order to store a reference to a parent or sibling node.
You can do that with boxes, but Arcs have benefits if you want your code to work in a multithreaded environment.
Does Rc<> help this much with async as well?
Wrapping everything in `Rc` is not a good default strategy. Instead figure out an architecture that works well with the borrow checker! This normally means thinking hard about your data structures and the ownership model of your application.
I love Rust precisely because of this. You can leverage the compiler to drive your development and design. If it's hard, then it's probably wrong!
Yes, I had the same experience writing code in Rust and Haskell. If the design works nicely with the language, then also the design is better, more modular, simpler dependencies and easier to understand and extend.
Trees and graphs?
However, that's not needed always. You largely wanna move stuff into closures in my experience, since the closure ends up owning the data.
Arc comes with a small performance overhead (Rc too, but less so I think?), so you don't want to use it all the time. When using Arc, you'll usually need a Mutex too, which adds its own cost, etc.
There are ways to partially avoid this costs, but they can add complexity (eg channels).
Sometimes you might be able to use an Async-flavor of the synchronization types instead, which come with more acceptable performance compromises in Async contexts.
* Rust traits are more flexible than C# interfaces, especially when combined with generics (implementing traits for foreign types, associated types, each method can have its own constraints, conditional trait implementation, #derive)
* Rust has much stronger thread safety guarantees (absence of data races, preventing access to a mutex's data without locking)
* Options are cleaner than null (though at least C# supports non-nullable reference types nowadays)
* Cleaner error handling through `Result`s. In C# you either have to use exceptions (discouraged for errors that are expected to happen), or use ad-hoc approaches which don't benefit from syntax sugar like the `?` operator.
* Support for discriminated unions ("enums")
* I like cargo better than msbuild+nuget ("it just works", feature-flags + conditional dependencies, distribution as source instead of binaries)
On the other hand C# has better IDEs and you don't have to deal with the rigors of ownership and the borrow checker. In particular I struggle with LINQ style functional programming in Rust, since the lifetimes of closures and the fields they close over are difficult to reason about.
I haven't used Kotlin, but expect it to be similar to C# in its strengths and weaknesses. Python is not an option for me, since I like static typing.
- GC pauses, Rc<T> does not, it's simply a deallocation by the last reference holder
- Rc<T> still has predictable memory allocation/deallocation, GC is not guaranteed to run until needed
- More efficient memory use, no need to keep track of allocated objects
- The rest of the Rust language is a pleasure to use (imo)
- Python is slow for certain applications, and not concurrent
- Kotlin is kind of more niche than Rust, it's very popular in the Android community, like C# is popular on Windows
Just my 2 cents, I love progamming in all languages. There are some use-cases where a high level language is absolutely the way to go. For others, Rust provides much more control with a handy escape hatch. Absolutely don't go wrapping everything in Rc<T> like a madman, only when the reduced complexity is more beneficial than dealing with references/lifetimes.
If anything, Rust with refcounts for everything is much closer to Swift.
One of its selling points is zero-cost abstractions and pretty powerful abstractions at that.
And of course, with Python your code will run 100x slower than either of the above, your dependency management will suck, you won't be able to statically compile, and to top it all off everyone will give you recommendations for your ailments which take a long time to try out and inevitably will fail miserably for one glaring reason or another. By way of example: "just rewrite the slow bits in C" -> you rewrite the slow bits in C -> your code is now slower because the marshaling costs exceed the gains + your build system is dramatically more complex and you have the sheer joy of debugging segfaults and undefined behavior (yeah, I know Cython exists).
If you need to do a lot of small allocation or have many circular references that you want to drop wholesale then you need a proper GC.
Even in some other cases you might benefit from proper GC. However Rust doesn't have a standard proper GC yet. It might have it as library some day. Some simple ones like https://docs.rs/gc/0.4.1/gc/ already exist.
But Rust is such a great language for many reasons. It would be a shame to not use it just because it doesn't have a great GC yet or because you don't have patience for borrow checker.
It essentially makes your code Java and defeats the point of the language.
I would expect most decent teams to reject your code during code reviews.
That's a pointless conclusion. The author's criticisms of Rust's tradeoffs are invalid because those are the tradeoffs Rust made. A perfect circle!
> Rust is not a language where first-class functions are ergonomic.
And this... I mean, I don't agree with her, but that might be because I've been immersed in Rust for half a decade. But Rust's tradeoffs are based around four things. It is a:
- performant - reliable (incl. memory safe) - productive - systems programming language
"Systems programming language" means no garbage collector. "Reliable" means you can't just pass around references to memory willy-nilly. I'm sure closures and their associated traits (Fn(), "call it as many times as you want", FnMut(), "call it only when certain safety conditions are satisfied", and FnOnce(), "call it once") could have been fine-tuned more, but they _do_ achieve the goal of general, usable (imo) first class functions.
I don't see another design that would have done this.
An opinion not shared by Xerox PARC folks, ETHZ or Microsoft Research.
As for the author being happier writing in a higher level language, it kind of proves the point that Rust's main target is the domain where any sort of automatic memory management aren't a viable option.
Pushing Rust outside of this domain is only trying to fit a square peg into a round hole.
You can explicitly decide what to copy inside a Rust closure as well, you just use a `move` closure and create references for anything you need referenced outside the closure instead.
It can: Box<dyn Fn(Arg) -> R + 'a>
This is just the general syntax for any trait object with a lifetime.
Pin exists so that references captured in Futures may be implemented via raw pointers. This implies that a Future contains pointers to itself, hence Pin.
The cost of Pin is that it forces you to write unsafe code as a matter of course, the so-called pin-projections. [1] Look at the requirements for structural pinning: they are quite complicated.
References captured in Futures probably could have been implemented differently: base + offset, or relocations, or limit what can be captured, or always Box the state for a Future that captures a reference. Those would have avoided a GC and been even safer, since it wouldn't require unsafe code on the part of struct implementors.
1: https://doc.rust-lang.org/std/pin/#projections-and-structura...
Pin is an evil, but it's the least evil of the possible options.
Anyways when I first tried async, I encountered structural pinning immediately, and I was surprised to learn that users are just expected to write unsafe code to participate in this system. Maybe it really is the best tradeoff but seems at odds with the rest of the language.
1. the example could have made a pure callback function that takes a mut& db param and pass thaf param to the 'do'er function. Why is this not required anyway? i.e. How does Rust know/decide who owns the mut& db if both the closure and the function that creates the closure can reference it?
2. as mentioned, the complaints about async seems to apply to closures in general even if used synchronously, AFAICT.
Best to think of this post as quirks when working with closures in Rust. It would have been far better to list each with workarounds.
No. If you did that, you could only pass functions in that took the db as a closure argument, nothing else... you're thinking about this example only, and forgetting the problem is with the general case of capturing whatever is needed for the callback to work.
> And then fast forward a few years and you have an entire language ecosystem built on top of the idea of making these Future objects that actually have a load of closures inside
And this sentence is wrong. There's next to no `Future` implementations which are built on top of callbacks. And the reason why that's the way it is is exactly the one the author mentions: Callbacks don't work very well with Rusts ownership model.
And this blog post from someone who did spend a lot of time working with async rust: https://tomaka.medium.com/a-look-back-at-asynchronous-rust-d...
It may be the case that there's no good way to solve them, but that doesn't mean that they aren't problems and it doesn't really help to say that people who highlight them are totally wrong and don't know what they're talking about.
That said I think your second link does a much better job of explaining the issues than this post does.
Apart from requiring a safe zero-copy io-uring abstraction to use a buffer pool instead of "bare" references, Rust's polling+cancellation model is fantastic. It's incredibly convenient to be able to externally time out and abort any Future, without needing to pass contexts/tokens and/or needing every I/O operation to have an explicit timeout option.
It's annoying when conscious small trade-offs are framed as fatal flaws (like the title of TFA). In the case of the cancellation model the "doesn't work" is that a safe abstraction is not entirely zero-cost. But when you use async in JS, C#, or Golang, you already have unavoidable heap allocations and memcpys (and another set of difficulties with cancellation). Rust's worst-case flaw is comparable to a normal mode of operation in a few other async languages. The scale of the issue is overblown, and its benefits are overlooked.
I am tempted from time to time to try Rust, but in the end, I don't think it provides enough benefits for me to consider it. I like high-level, and when I am going low-level, I don't want to be hand-cuffed. It seems with Rust, I am paying all the time just for the ability to go into hand-cuffed low-level mode.
If you care about developer speed and security but don't care about correctness or performance you can rely on someone's else implementation and write higher level code (eg. use node and offload low level security considerations to node).
If you care about developer speed and performance but don't care about correctness or security use a low level unbounded language (eg. write C and triple check your code)
If you care about security, correctness and performance but don't care about developer speed, use Rust.
To be frank I find the point about developer speed in Rust to be a bit exaggerated, it's pretty high level and the tooling is pretty great.
- Compiler speed is a bit hit or miss - Debugging life cycles definitely take some time, but with time you get the hang of it and you can quickly copy paste previous solutions to the current problem. - You save a significant amount of developer time by fixing things alerted by the compiler instead of finding errors at runtime
All things considered Rust is definitely the language I feel more productive in (before it used to be Haskell).
Oftentimes considerations about hiring / collaborating with other developers take the precedence over security, correctness and performance.
Right now I'm maintaining a node.js project, 2 Python projects and a Rust project - mainly because node.js and Python worked best with those teams and the Rust one is a solo project.
Rust has a long learning curve that most people won’t make it through. For them, they might feel the language is slow to developenin because they haven’t gotten to the point where they are “thinking” in Rust.
As a Haskeller, you are well suited to learn Rust; due to their similar ML lineage (the original Rust compiler was written in OCaml), Rust and Haskell make some similar design considerations. I’d say one thing Rust does right is take a lot of the things that make Haskell safe and make them fit in an imperative language.
I am thinking TypeScript might give the biggest bang for the buck: * You have the widest possible reach via web apps & Electron * You have an eval/Function object for compiling code on the fly * You can embed low-level code via WebAssembly (and here Rust might be relevant for producing that WebAssembly) * If you need access to your TypeScript libraries on mobile, you can still do that via embedding a hidden WebView.
Most of the time, particularly if you're not writing libraries, Rust feels like a dialect of Python that wants to help you get things right.
Things of course would be different should the client insist on implementation done in Rust but so far not a single client of mine ever mentioned using this language.
The problem is that most likely those mediocre C++ developers won't be able to write any Rust at all.
If you do have good C++ developers, you're also probably better off sticking to well-established and battle-proven C++.
So the use case for Rust remains niche. It's a way to attract the programming language nerd that knows more about Haskell than he does about systems programming. Maybe not exactly the best fit? But worth trying if you want to differentiate yourself from the competition.
And the complaint is that Rust semantics makes this hard. Well yes, Rust makes it uncomfortable to shoot your own foot, that’s kind of the point.
I think you are misunderstanding the author's point. I think that they'd probably agree that the (lack of) ergonomics of closures are a necessary result of the safeguards that Rust provides.
They point is more that, given that closures have somewhat frustrating ergonomics, it was probably a bad choice to base Rust's primary concurrency system on closures.
Disclaimer: this is not my opinion, just paraphrasing what I believe the author's point is. I found the post a bit strange, it seems to end rather abruptly. It doesn't seem to address the main question it seems to raise: what does this mean for async Rust and why is this bad?
Rust still doesn't support use-after-free, so you can't reference a temporary object and use it in another thread that will outlive it :)
In TFA the second do_work_and_then() example doesn't compile, because it has a UAF vulnerability that borrow checker has detected and prevented.
https://doc.rust-lang.org/std/mem/index.html
Genuine question, I don't mess around with memory typically.
The `&mut Database` sort of implies that the Database handle doesn't do its own locking or other needed state tracking - it just relies on the exclusivity of `&mut` in Rust to be sure that nobody else is modifying the database handle at the same time.
If the API used `&Database`, then it would have to be more flexible for simultaneous use of the handle. And then the closure would be (a bit) easier to call too, because it's not tracking that exclusive reference.
If the API used a reference counted `Database` handle, then it would release even more restrictions of lifetime management, etc. You can implement all of these in Rust.
In other languages, you usually end up with alternative two or three.
If you try to simultaneously take alternative 1 and use it in a way that's not supported, that would be shooting yourself in the foot. Except Rust says compile error instead.
my_fn(|| {
db.store(42);
});
db.drop();
(Assuming you can just drop the database object, the semantics don’t really matter but the idea is the same.) The OP wants an easy way to do this but this is just not an easy thing to do. How can the closure guarantee that the database object will exist if my_fn decides to sleep for a couple seconds? Most languages do not have this problem because either: they use a garbage collector (Java and it’s cousins, Python, Go) or they are not safe (C, C++). Rust is in a particularly difficult (and ambitious and exciting!) intersection where this problem is tricky.The closure can write to database, and after the call, there’s no way to know if it has already written, or even if it’s writing to it right now.
Some patterns around error handling still a bit awkward, but the FuturesExt and TryFuturesExt traits help a lot there.
My only real “I have no clue what’s going on” moment so far has been with an error about traits not being general enough, but someone on the rust forums helped me out: https://users.rust-lang.org/t/trait-is-not-general-enough-fo...
Setting up clippy to disallow non-send-sync futures throughout the codebase has prevented that particular thing from recurring.
Then the last paragraph just say "Oh and asynchronous Rust is even worse."
But why is Rust so much harder than any other newish programs language.
Dart is like all of my dreams come true at once, Rust still gives me nightmares. I seriously tried to learn it multiple times and failed repeatedly.
I've created several Dart/ Flutter projects for myself and friends. Multiple C#/Unity projects. Python and JavaScript have paid my rent for the better part of a decade.
But Rust, I can't grasp basic concepts.
All the languages you cited are essentially in the same space, they're runtime-heavy GC'd ("managed"), imperative, object-oriented, "applications" languages.
Rust tries to achieve memory-safety without runtime support (as well as low-overhead in general), and to do that it relies on a rather advanced type system with concepts which aren't formal in many commonly used languages (e.g. borrowing and affine types).
It's a different language, and if you approach it with the expectation that it's similar to other languages you know, it's probably not going to work well. Possibly unless the language in question is C++ (as Rust formalises a lot of best practices of C++), but even then the lack of object orientation and strictness of the compiler is going to make the transition difficult.
It's probably easier for people with less expectations that "all languages are similar" and that their knowledge will be easily transferrable, either because they have less experience period, or because they have experience with a much wider range of languages.
Dart is the worst new language I've tried and it should have died back when they (in retrospective rightfully) abandoned DartVM in Chrome plans. (FWIW I used Dart back in the AngularDart betas, before Angular 2.0 was released, when TypeScript didn't even have support for async/await. Back then Dart had some good ideas, the tooling was good and it looked promising. In the meantime TypeScript did everything better while being backwards compatible and JavaScript improved a lot, along with the tooling. Now days Dart is strictly inferior in my view, the object model is closed/static, type system is nominal, so it has none of the scripting language qualities, and the runtime/metaprogramming is limited, with shitty library ecosystem - it's a shittier version of Java.
It's a language designed by VM developers and it shows in every way possible, so much emphasis placed on how the implementation works - for a high level language that isn't that performant in the end anyway and is hardly the bottleneck in it's usage scenarios.
Meta programming is done with compile time code generation and there is no runtime reflection, look at the libraries built for dealing with immutability for example - the ergonomics are Java level bad.
Flutter is a good idea if you need to write cross platform LOB apps (it becomes a bad idea if you need to use native components and render in coordination with them because the async channel native communication introduces visible render lag, eg. if you try to build custom rendering overlays over native maps it will lag frames behind because by the time you receive the map viewport updates and rerender the native map moved forward).
The fact that Flutter is built on top of Dart means I will not touch that framework any time soon, and would recommend anyone who doesn't like writing Java style boilerplate to avoid it as well.
They would need to include serious quality of life features to the language, and these features were requested years ago, but they move at a snails pace and prioritise other stuff.
Why do I still need a bunch of weird configuration files to just get import working ? JavaScript has treated me very well, it's what allows me to pay my bills. It still has so many fundamental issues that I avoid it when I can.
The vast majority of apps ultimately either CRUD or LOB( thanks for the term). When I or a friend needs something hacked together real quick, Flutter is the answer.
Add in what might be the greatest Firebase integration, and that you can create CRUD apps in hours. Implement login, and authentication flows within minutes.
I don't feel like playing the true Scotsman game when it comes to getting things done, if it works it works.
In fact when I build these tools for my friends, or for myself I don't even build an app. I deploy directly to a website with Firebase and Flutter web. Google makes us workflow insanely easy, I could probably deploy a new CRUD app with a login system in like an hour.
Ultimately all we need to do is render a list of items, create new items, update them and delete them. That's what the vast majority of apps do.
At least for my personal projects it's Unity for games, and Flutter for anything else.
Then again, I don't have a comp science background and I just love getting things done. I don't really care how Flutter accomplishes what it does. Your allowed to use both Dynamics and Types when defining methods. This really helps when trying to hack something together fast, but latter reffing it.
If a friend needs an app built to track grocery spending or what not, what stack would you pick.
The language itself seems ok too. If I didn't have the IDE tools to tell me what was wrong I'd be screwed, but once you run into your first few borrow checker issues you'll read up on what's actually going on and you can fix the problem.
Even the async stuff that the guy is writing about, I don't recognize. Normally async causes all sorts of issues, especially ones where you're totally stumped and the errors make no sense.
With Rust it's just been a breeze. Write some code and at some point the compile will heavily hint not to go that way. Especially with shared state type systems, a borrowing this way and that, you'll find that it's smarter to rethink the arch rather than add yet another Arc<RwLock<>>.
For one, Rust has manual memory management. You are aided by the type system and the compiler, but it's the programmer who has to deal with the mental load of thinking about the lifetime aspects of every variable. Compare to a GCed language, where you just free your mind and can focus on your program.
However, anyone came from a systems programming background and wrote any non-trivial async network applications in C/C++ will most certainly appreciate the abstraction and safety Rust provides. Productivity grows significantly when writing in Rust because a lot of the low level details are handled by library authors instead of the programmer.
What problems did you encounter when learning OCaml?
You must be intentional about both coding and systemically learning at the same time how it works. Watch YouTube videos plus build a real world project.
My first attempt to learn rust failed. My second attempt was much better.
The current async story is still an MVP and I too dislike it. In the months before async, the ecosystem seemed on halt, waiting for async to land on stable Rust. Since then nothing has changed. The ecosystem "degraded" noticeable and has not recovered since. Maybe in future async will be great, but right now I try to avoid it.
... I still love Rust
https://lib.rs/crates/tokio/rev
And Rust as a whole keeps growing exponentially:
My point is, the ecosystem experience has degraded since the async MVP is stabel.
The split between blocking and non-blocking code existed in Rust before stabilization of async/await (e.g. futures 0.1 existed 3 years before, and mio is older than even Rust 1.0).
The only new thing is async-std, but that's not a stabilized part of Rust. It's just a 3rd party library. It may have been written anyway. It's relatively niche (1/10th of tokio), and you can safely ignore its existence (as far as I can tell every async-std-based crate supports tokio too, or has a direct tokio equivalent.)
I was worried that switch from futures 0.1 to std::future would fragment the ecosystem, but fortunately the whole ecosystem moved quickly, and the switch is completely over now.
Seems like they just tried to be everything at once, and reached some sort of a critical mass. It probably didn't help how Mozilla dropped lots of their Rust projects and staff at roughly the same time.
It's still a very good C++ replacement. I think its role as a higher level application language is more of an open question.
The key insight here is that garbage collection gives you access to a variety of patterns that are otherwise fiendishly difficult to implement safely, including non-leaking closures, RCU-like resource sharing, and fast (but safe!) bump-pointer allocation of short-lived objects. Honestly, something like typed Python or Typescript is going to be fast enough for most use-cases, especially if any compute-heavy parts thunk out to optimized C++ or Rust. And if those aren't fast enough, you can write against the JVM or the CLR in a variety of beautiful, expressive languages and still gain the benefit of a GCed, managed environment while retaining the ability to accelerate core kernels in native code.
Writing entire big systems in C++, Rust, etc. just doesn't make much sense to me. Yeah, I understand the benefits of technical uniformity, of having to train people to use only one language, and of easy of debugging when there's only one level of the stack --- but still, I think people use low level systems languages for too much, and these articles about asynchronous work being hard to write in Rust are symptomatic of this fundamental mismatch.
So, people from Google have explained about this before. The idea you have assumes that if you speed profile the code, 99% of samples land in this function "A()" and so you just re-write that part in C++ and now it's faster, or if you measure allocations you find 99% of RAM was allocated by "B()" and so you just re-write that part in C++ and now it uses less RAM.
Google already did all that low-hanging fruit. When they run the profile it comes back flat. You should rewrite A, B, D, E, F, J, K, L, M, N ... in other words the way to make the system faster is to just write it in C++
Part of this is also scale. If a system I run once week is a little slow, maybe in some sense that costs 40¢ but I don't account for it. At a mid-size non-IT firm maybe a similar performance cost is $1000 per year. Just about worth somebody enquiring if it can be sped up, but not worth arguing about it if the answer is "No". Maybe a mid-size IT firm where you work spends $1k per month on this problem. You could speed it up by rewriting the whole system, this would take some time - how many days work before it's cheaper to leave the problem than pay you to fix it? However, at Google's scale maybe that problem costs them $1M per week. They can justify assigning a whole team to fix that because of scale.
1) the expressive type system, notably the use of optional type instead of null and the use of lifetimes to make reasoning about references tractable, and 2) the community, with a focus on correctness, documentation, and being welcoming.
I think this is the most underappreciated part of this article. Since when did everything have to be async? There are other ways to represent concurrency that more accurately reflect what the computer is actually doing.
For example, an alternative to async is to represent a workstream as a state machine, where state transitions happen between I/O. Then, your state machine can be a struct, and each state transition can be an impl function on that struct that takes one or more completed I/O requests as input and emits one or more I/O requests as output. This saves you from having to implement everything as a closure, which this article rants about. Your top-level epoll loop merely services I/O requests from state machine instances, and invokes your global application logic to start and stop state machines to carry out business logic tasks.
I realize that many complicated workstreams could have many states due to all the I/O they might do, but the task of converting a high-level workstream into a state machine could be automated by the tooling.
That tooling is literally async/await. async/await transforms functions into state machines
> I think this is the most underappreciated part of this article.
I think it's incredibly silly actually. Abandon all async for a difficult and error prone epoll model?
> Since when did everything have to be async?
It doesn't! No one is forcing anyone to use async. I'm not sure why the author implies that.
But if you do want to use async, Rust is attempting to solve the async problem with the same guarantees it has for blocking code. Turns out that is hard.
Well, hang on there... this isn't entirely fair.
Rust does not force you to be async, but the community in some ways pushes you to be async even where it might not make sense for it to be the default. I can't say for certain (and this is all my opinion, to be clear) but it feels like this started happening when async-fervor hit its peak.
My go-to example is reqwest, which if you want a blocking HTTP call, still just needs all of Tokio in the background. I find it really odd that the blocking API is just a wrapper for a finagled async API; if I'm choosing the blocking one, I probably don't want Tokio in my project.
There are other HTTP request libraries, to be clear - but they're often less battle tested and/or have their own lurking bugs. Reqwest is the de-facto one and it'd be nice to be able to use it without the heaviness it brings in.
Depending on the domain you're programming in, it can often feel like async-by-default is the norm. It can be frustrating in Rust.
(It's nowhere near enough to deter me from using the language, mind you)
I think a blocking implementation being a `await(async impl)` is typically fine...
the problem with that is the lack of async interop in the current state of things, more than the async runtime which mostly gets compiled away.
/// A state machine that adds three numbers and uploads them to a web server
struct AddAndUpload {
/// I/O handle to the event loop
io: IOClient,
/// Buffer to store numbers I load
nums: [u64; 3],
/// URL to upload the data to
url: String
}
impl AddAndUpload {
/// Constructor
pub fn new(io: IOClient, url: String) -> AddAndUpload {
AddAndUpload {
io,
nums: [0u64; 3],
url
}
}
/// Entry point to this state machine
pub fn inner_main(&mut self) -> Result<(), IOClient::Error> {
/// go and get the data
let n1_fut : IOClient::Future<u64> = self.io.sql_async("SELECT n1 FROM table1", &[])?;
let n2_fut : IOClient::Future<u64> = self.io.sql_async("SELECT n2 FROM table2", &[])?;
let n3_fut : IOClient::Future<u64> = self.io.sql_async("SELECT n3 FROM table3", &[])?;
// wait for all I/O operations to finish
IOClient::wait_all(&[&n1_fut, &n2_fut, &n3_fut])?;
// extract results
let n1 = n1_fut.into_inner();
let n2 = n2_fut.into_inner();
let n3 = n3_fut.into_inner();
// upload them
let sum = n1 + n2 + n3;
let upload_fut : IOClient::Future<IOClient::HTTPStatus> = self.io.http_post_async(&self.url, &["content-type: application/octet-stream"], &sum.to_be_bytes())?;
let upload_http_status = upload_fut.wait()?.into_inner();
match upload_http_status.as_u16() {
200 => {
Ok(())
}
400..499 => {
Err(IOClient::Error::Custom("client error"))
}
500..599 => {
Err(IOClient::Error::Custom("server error"))
}
x => {
Err(IOClient::Error::Custom("Nonsensical HTTP code"))
}
}
}
}
impl IOClient::StateMachine for AddAndUpload {
type Return = ();
fn main(&mut self) -> Result<(), IOClient::Error> {
self.inner_main()
}
}
/\* somewhere else \*/
fn main() {
let io_server = IOServer::spawn().unwrap();
let io_client = io_server.client().unwrap();
let add_and_upload = AddAndUpload::new(io_client, "http://example.com".to_string());
loop {
io_server.run().unwrap();
match add_and_upload.get_machine_status() {
Ok(IOClient::StateMachine::Finished(result)) => {
eprintln!("add_and_uploaded exited with {:?}", &result);
break;
}
Ok(_) => {},
Err(e) => {
panic!("add_and_upload aborted: {:?}", &e);
}
}
}
io_server.terminate();
}your statemachine blocks the thread. if you had a more complicated state machine, maybe nested machines, theyd block each other because they dont know how to cooperate.
Using callbacks in Rust is not idiomatic, at least I haven't seen such code over the last two years writing Rust, and Rust syntax and semantics with life times is not tailored toward that approach.
So the author forces an async style on Rust that it was not build for and then complaints.
I guess I’ll have to become an expert to find my disappointment.
It doesn't have much to do with async, despite the title. Async works just fine.
Async is bread and butter of JS and you rarely have any larger bits of sync code, so you learn to deal with this.
And then being able to just freely pass bits of data accessing code (closures) around is such wonderful feeling that you'll miss it everywhere else you go.
I recently had a little excursion into Python and had to invent a very nasty hack to concisely keep short bits of code accessible through some constants.
This is my major reason for using Rust. It's far better to beat your head against a wall when you're writing than when you're debugging. In both c++ and c# it's possible to write subtly wrong code that is basically undebuggable. Often these are intermittent things that show up once every million or more runs. There's no amount of time that will satisfy you after you've run into this, even after you've fixed the problem. It's like having a stalker, you never know if they've stopped stalking you. You can lock your doors, you can buy an alarm system (eg Valgrind suite). But you won't know whether you've really solved the issue.
Of course it's possible there will be other undebuggable issues with Rust, I'm going more by reputation and general impression in blogspace rather than a thorough study. But I thought it was worth a try, and I've been positively impressed thus far.
Experience tells us that humans can't successfully reason about non-trivial concurrent programs unless they exhibit Sequential Consistency. In Rust you're promised this is what you get. Maybe what you wrote is stupid and wrong, but it has Sequential Consistency. "Oh," you exclaim during debugging, "A might happened before B and then we're in a pretty pickle" - you found the bug, now you just need to fix it. This promise is delivered by never allowing code to have references to things some other code might change, thus eliminating data races.
In most other languages that offer concurrency this promise only applies if you wrote a program with no data races and the responsibility to ensure that is with you, so you can accidentally write programs that don't have Sequential Consistency and thus... "Wait, so, A happened before B and B happened before A? Huh? I don't even understand the bug".
Personally I hate dependencies in general and try to minimize them. Instead of reaching for a utility crate I think “how could I architect this so I don’t need this hack?” There is almost always a way. In the end falling back on Arc<> is still cleaner and probably comes with less overhead than dependency spaghetti.
But yeah, the way Erlang embededded the actor pattern in the VM (Beam) and the language itself is great.
Tough personally I would have liked it if it was more statically typed. I still need to take a look at Gleam...
[0]: https://caramel.run/
I didn't quite get the gist of the article though, isn't the whole point of async-await to get rid of passing callback function pointers around? What do closures have to do with async-await in Rust?
Mind, it is not going to be fast as it is going to be hard to generate efficient code ...
Well, space _blocking runs blocking code in an async context. It takes a closure as it's argument and if you're in a mixed async/sync platform you will his this function a lot. To deal with it you end up needing to use move. And to use move you need to clone your pointers to the data and manage all that guff.
The alternatives are Arc, deep copies, or use C++ where you will invariably get it wrong and end up with corrupted data and a very bad week (or you don't notice and reply to this comment saying that you do this in C++ and never had a problem)
The title is clickbait, of course aync Rust works, and the article doesn't talk about it anyway. The only mention of async is an observation that it's CPS under that hood, followed by a wandering rant about CPS that fails to account for the design constraints.
In the end, the author suggests forcing every AIO user to manually write out their polling loops, which is simply a silly idea. At least if their recommendation was a completion-based API without language support they would seem serious.
I have found that async or even in Go with goroutines, a large amount of small threads are not faster even if they should be in theory when it comes to CPU intensive work.
I use it to generate a 3D universe (at the atomic level) but store the data as enums.
Here is the repo: https://github.com/selfup/oxidizy
Big help from rayon:
1) https://github.com/selfup/oxidizy/blob/master/crates/unigen/...
2) https://github.com/selfup/oxidizy/blob/master/crates/unigen/...
3) https://github.com/selfup/oxidizy/blob/master/crates/unigen/...
Example perf generating an obscene amount of data on a 32GB machine with 16 threads (3800x):
Atoms: 110592000 Baryons: 26099712000 Quarks: 78299136000
real 0m12.779s user 0m0.000s sys 0m0.000s
I really don't like futures/promises, I don't know where this abstraction came from.
Callbacks are where it's at. Someone, somewhere has to write callback code; they cannot be got rid of. What works for me is keeping the callback handler as short as possible, this usually means just pushing 'work' onto an async queue that is serviced by one or more threads.
async/await often requires very little changes compared to synchronous code, whereas reworking a program into callbacks is much more impactful. & the async/await compilation process tends to produce better performance in addition to this. My first async/await work was a few years ago to increase a data importer's performance by an order of magnitude compared to the blocking code (I also used it a couple years earlier for a GUI (PointerWare) where code would await opening new windows, it wasn't really being used for concurrency there, just a nice interface of "show pop up, wait on that view to complete" which made Back buttons easy)
Here's an example where looping made for a callback that recursively called, using async/await I get to use a plain loop:
before: https://github.com/serprex/Befunge/blob/946ea0024c4d87a1b75d...
after: https://github.com/serprex/Befunge/blob/9677ddddb7a26b7a17dd...
Callbacks make it difficult to send information up the call chain, as the caller fires it off without a ticket to wait on the result. libxcb is an example of a library which optimized on libx11 by having functions which return cookies which func_reply wait on, these functions could similarly be implemented as an async/await interface
I don't see why people find it so complicated to separate begin-compute & wait-on-compute
I've rewritten a nodejs game server into rust, https://github.com/serprex/openEtG/tree/master/src/rs/server... handleget/handlews are quite straight forward. But apparently it doesn't work
Exactly! Making a thread block waiting for a result isn't true async in my book. It doesn't matter that the result is going to come from another thread. Futures/Promises make you block a thread.
Performance numbers don't care what's in your book
I don't really do JS, where a lot of this seems to be happening, but the code I have seen with the huge ladders of callbacks doesn't seem so great to work with to me.
Also, although using promises seems better, it seems like it could quickly become spaghetti.
Now, you may think this can be done in C with the `select()` API and many switch statements. And you would be correct. All these "async" languages and framework are wrappers around this that let you write your code in a procedural manner, and take care of the select and switch for you.
Having never worked with threads heavily, they always seemed like WAY more hassle to me. I assume that‘s the alternative? I think go has something else?
If you specifically mean async/await syntax, let me illustrate with a contrived example. It can let you express a sequence of asynchronous operations in a more natural way:
function promised(cache, db, metrics) {
return cache.query(...).then(cachedResult => {
if (cachedResult) {
return cachedResult;
} else {
return db.query(...).then(dbResult => {
return cache.store(dbResult).then(_ => dbResult);
});
}
}).then(finalResult => {
metrics.log(...);
return finalResult;
});
}
async function awaited(cache, db, metrics) {
let result = await cache.query(...);
if (!result) {
result = await db.query(...);
await cache.store(result);
}
metrics.log(...);
return result;
}Why not just arrange it like this?
function non_awaited(cache, db, metrics) {
let result = cache.query(...);
if (!result) {
result = db.query(...);
cache.store(result);
}
metrics.log(...);
return result;
}
Basically doesn't a good threading library just allow you to make all those 'awaits' implicit?I mean just because await isn't explicitly there, if I run the function above in a thread, my understanding is that the thread does yield to other threads while waiting for I/O.
It's not as if it busy-loops while waiting or something.
As designed, calling an async function just returns a Promise, and any Promise can be awaited. This means that I can pass that Promise around, and it also means I can use a Promise-based library (of which there are many) easily from within my async code.
An example? What if I want to launch multiple asynchronous tasks in parallel, and then either wait until the first one finishes (a race) or wait until they all finish? Without explicit await, we'd need some syntax to express this. With explicit await, I can store the Promise and then await it when desired, like this:
//start both tasks in parallel
let fileDataPromise = getFileDataAsync();
let netDataPromise = getNetDataAsync();
//wait until both are finished
let fileData = await fileDataPromise;
let netData = await netDataPromise;
Fortunately there are nice standard library functions for transforming collections of Promises, so we can also just write: let [fileData, netData] = await Promise.all([
getFileDataAsync(),
getNetDataAsync()
]);The utility of native async is when you spawn multiple async tasks before awaiting. This is cheaper than spinning up some threads or handing off to a threadpool.
Well actually it is supposed to make concurrency easier for programmers.
What would you say is an "easy" way to deal with concurrency? Handle threading, memory visibility issues, locking, etc yourself? Doing it "reactive"? I guess personally I too would say something messaging based such as the actor pattern but not everything is a good fit for that model.
Async is intended to be a more generic (ie. fit for everything) and easy way to program. I'm not saying it succeeds in that but the goal wasn't to save the computer the effort.
Well maybe this isn't the best example because you already have iterators for the plain iteration part; however let's say you wanted to make an iterator for a container that needs async to iterate the data, then you find yourself having the same problem that the existing facilities making use of the old "non-async" iterators become useless.
Alternatively you let async leak into _everything_, even if they are not actually using async themselves.
There's nothing wrong with runtime-driven schedulers handling the threads for you, but async isn't the only way to do it. But it is one of the easy ways to do it and a way that is implementable as a library.
In particular single-threaded async (javascript) can be painful because you need to be mindful about not doing anything for "too long" without splitting the work into several parts. In a sense with async we're back in the era of co-operating scheduling. Even in multi-threaded environment is can be based on luck or faith that not all the threads allocated happen to get stuck on long-running jobs when short and fast user-facing interactive async tasks are starving. (A problem solved by over-allocating threads of course.)
It should be noted that this is only if the type-system in your language is unable to properly abstract over containers and their capabilities.
If it is powerful enough however, then you can write the code once, under the (important!) assumption of short-circuiting in the case of errors.
The Beam/Erlang/Elixir model. It's a bit more constraining but it's just so clean and reliable, and processes having individual mailboxes makes it much simpler than having to wonder what synchronisation primitives to use, then decide how to share them (globals? parameters? others?).
Just get a reference to a process and you can send it messages, simple. If you want replies, send it your address. Also simple. And matches the real world very, very well (at least the real world of a few years back when you'd send letters through the mail, electronic communication channels tend to be more full-duplex).
I agree. But I think that only works if you embed it in the language like Erlang did. If you make it optional you get libraries which use different models, people still making concurrency mistakes, etc.
But for more generic languages then Erlang such as Rust (or Java, C#, etc.) this simply isn't an option. Because the actor pattern is too opinionated to be a fix for all.
Threads and queues are pretty easy to reason about too — just avoid locks and shared memory.
Message queues, with workers atomically reading messages of a single queue, and placing responses on another queue.
Sure, it's not as flexible as starting threads[1], but 99 times out of a 100 you can use message queues and there's literally no race condition to happen, no memory visibility issues, no locking, etc.
[1] Some solutions, such as those that games employ, are rarely able to implement concurrency with just message queues, but to be honest if your problem is such that you can only employ solutions that require global state to be modified by several threads, then Rust, and similar 'safe' languages aren't usable there either.
It is another programming paradigm. It has its uses. It has its drawbacks.
“Ruining everything” is a big stretch.
The issue of coroutine-based async is that a coroutine does not do anything until it's awaited (and the chain goes up to the reactor), so in Python when you create a coroutine nothing happens. This is unlike Javascript or C# (IIRC) where the baseline awaitable is a task, with tasks awaiting is a synchronisation point, but if you create a task and drop it the task will go and do its own thing.
In Rust, this is mitigated by `[must_use]`, so the compiler will warn you when you've created a coroutine (Future) and dropped it on the floor, not so Python, you just get a warning when the runtime shuts down, it's way harder to track missing awaits.
Except Rust has no GC…
Maybe this guy needs to just stick to Lisp.
This is why he's got a problem, in a nutshell. I suspect the author has a heavy Javascript background and is used to Continuation Passing Style (CPS)[1]. The problem is that in a non-interpreted language that is a horrible way to do things because of scope and references. A better approach is to use messages from your thread. In C++ you could do this with ZeroMQ inproc sockets [2], or other mechanisms. In JAVA you could use a number of methods, such as a ConcurrentLinkedQueue [3]. In Go, you have channels [4]. In Rust, you have..well, also channels. Rust By Example already has a similar example that uses channels [5]. The concept of a Message Passing Interface (MPI) works amazingly well, and there is at least one flavor implemented for all the major languages (and often more).
The only languages I've seen that get callback style interfaces done well are Clojure, Lisp, Erlang, and Elixir.
The only thing I've seen that's better than MPI, in some situations, is Tuple Spaces [6].
Tar and feather me for it, but I miss JINI [7] and JavaSpaces [8] when I have to do a system in JAVA. JINI is now Apache River [9], but the last release was 2016.
[1] https://en.wikipedia.org/wiki/Continuation-passing_style
[2] http://api.zeromq.org/2-1:zmq-inproc
[3] https://docs.oracle.com/javase/9/docs/api/java/util/concurre...
[4] https://gobyexample.com/channels
[5] https://doc.rust-lang.org/rust-by-example/std_misc/channels....
[6] https://software-carpentry.org/blog/2011/03/tuple-spaces-or-...
[7] https://en.wikipedia.org/wiki/Jini
[8]https://river.apache.org/release-doc/current/specs/html/js-s...
It's not that Rust doesn't work; it's that you're misusing Rust.