349 points · by JoshTriplett · 7y ago · 234 comments
What do I gain if I have code like this [0], which has a bunch of `.await?` in sequence?
I know .await != join_thread(), but doesn't execution of the current scope of code halt while it waits for the future we are `.await`-ing to complete?
I know this allows the executor to go poll other futures. But if we haven't explicitly spawned more futures concurrently, via something like task::spawn() or thread::spawn(), then there's nothing else the cpu can possible do in our process?
[0] https://github.com/async-rs/async-std/blob/master/examples/t...
Same code flow just it allows you to launch the same thing multiple times without having to wait for the whole thing to finish sequentially or wait on the OS to handle your threads.
As soon as you do that, your code isn't async anymore. And if you're using a framework like Vert.X or node that only runs one thread per core you're in big trouble.
The most reasonable answer I've seen to all this is Java's Project Loom. An attempt to make fibers transparently act like threads, so you can use regular threaded libraries as async code.
Rust is going to have the same problem Java does with async. A lot of code was written way before async was available, and it not always obvious whether something blocks.
If the executor is Tokio, it’s built on mio which will use one of kqueue, epoll or iocp depending on the platform: https://docs.rs/mio/0.6.19/mio/struct.Poll.html#implementati...
Here is synchronous code:
result = server.getStuff()
print(result)
Here is synchronous code, that tries to be asynchronous: server.getStuff(lambda result: print(result))
Once server.getStuff returns, the callback passed to it is called with the result.Here is the same code with async/await:
result = await server.getStuff()
print(result)
Internally, the compiler rewrites it to (roughly) the second form. That's called a continuation.That's pretty much it.
A more involved example.
Synchronous code:
result = server.getStuff()
second = server.getMoreStuff(result+1)
print(result)
Synchronous code that tries to be asynchronous: server.getStuff(
lambda result: server.getMoreStuff(
result+1,
lambda result2: print(result2)
))
A lot of JS code used to look like this hideous monstrosity.Async/await version:
result = await server.getStuff()
second = await server.getMoreStuff(result+1)
print(result)
Remember again, that it is basically transformed by the compiler into the second form. result = await server.getStuff()
second = await server.getMoreStuff(result+1)
print(result)
`await getStuff()` MUST terminate before `await getMoreStuff() ` begins. So this chunk alone is analagous to synchronous code, unless we're in the middle of a spawned task, and there are other spawned tasks in the executor that can be picked up.Async/await is really popular in the JavaScript community because in web apps, you usually only have a single thread of execution which you share with the browser UI code. So if your code made a network request synchronously, the user might not be able to scroll or click links or anything until it finished.
Frankly, in the case of sequential flow like the above, I would rather write
result = server.getStuff()
second = server.getMoreStuff(result+1)
print(result)
and have the runtime automatically perform work-stealing for me. No need for awaits. They just litter the code. This is what Go does.Indeed, since you mention continuations, I'm sure you realize that they're more or less callbacks.
server.getStuff(gotStuff)
server.getMoreStuff(gotMoreStuff)
Just using functions is more simple and also more powerful.
A function being async usually means stuff will happen, things can go wrong, and you might want to do different things depending on the response or whether it failed.Where await is useful though is in serial execution of async functions that really should be sync, but them being async is an optimization in order to not block the thread.
It is really unfortunately that so much extra crud had to be introduced to JS (corutines, async, promises) in order to be able to await. Reading complex Promise based code is very unplesent, with async functions pretending to be pure, without any error handling, full of side effects, and omitted returns.
With callbacks we had inexperienced programmers writing pyramids of callbacks and if logic. But it was not that bad, as the complexity was in your face, and not hidden under layers of leaky abstraction.
You are correct. In edge cases where there is only 1 await in the queue for 1 process with 1 thread you gain nothing.
But you're accurately describing an edge case where await has limited value.
Await's true power shows up when you anticipate having multiple in-flight operations that all will, at overlapping points, be waiting on something.
Rather than consume the current thread while waiting, you're telling the run-time, go ahead and resume another task that has reached the end of its await.
This was possible before using various asynchronous design patterns, but all of them were clunky, in that they required boilerplate code to do what the compiler should be able to figure out on its own:
"Hey, runtime. This is an asynchronous call. Go do something useful with this thread and get back to me."
Second, await is MUCH EASIER for future developers to process because it looks exactly like any other method call and makes it easy to reason about the logic flow of the code.
Rather than chasing down async callbacks and other boilerplate concepts to manually handle asynchronous requests, the code reads like its synchronous twin.
int a = await EasyToFollowAsyncIntent();
This makes the code much easier to reason about.
To me those are the 2 biggest gains from async.
1. Less boilerplate code for asynchronous calls.
2. Code remains linearly readable despite being highly asynchronous.
For a more complex networked application, we have the tutorial here: https://github.com/async-rs/a-chat
I think the expectation with Rust async-await at the moment is likely that people are familiar with async syntax from other languages e.g. Python - it's not even in beta yet, you need to be running nightly to get the syntax.
If there was another future spawned then the await would cause the runtime to sit there until either of the futures completed. The code would attend to the first future that completes intil that hits an await.
Async is just a way to get cooperative threads compiled to a static state machine, trading lower concurrent utilization and throughput for less context switch overhead and lower latency.
Now imagine that you spawned a few hundred of them with JoinAll. Each would run, multiplexed within a single thread, with execution being passed at the await points.
* anyone know the correct nomenclature for this? Single-coroutine?
1. Get used to callbacks in NodeJS, for example write some code using fs that reads the content of a file, then provide a callback to print that content.
2. Get used to promises in NodeJS, for example turn the code in #1 into a promise by creating a function with that calls the success/reject handler as appropriate on the callback from opening that file. Then use the promise to open the file and use .then(...) to handle the action.
3. Now do it in async. You have the promise, so you just need to await it and you can inline it.
By doing it in the 3 steps I find it is more clear what is really happening with async/await.
If you have an async method that can wait for input on both devices, you can await the results of both of them, and they won't block eachother.
Nope, async really isn't trivial.
> I know .await != join_thread(), but doesn't execution of the current scope of code halt while it waits for the future we are `.await`-ing to complete?
It doesn't, that's the charm of it.
It's best to treat 'await' as syntactic sugar, and to dig in to the underlying concepts.
I realise we're not talking C#/.Net, but that's what I know: in .Net, your function might do slow IO (network activity, say) then process the result to produce an int. Your function will have a return-type of `Task<int>`. Your function will quickly return a non-completed Task object, which will enter a completed state only once the network activity has concluded and processing has occurred to give the final `int` value.
The caller of your function can use the `Task#ContinueWith` method, which enqueues work to occur if/when the Task completes, using the result value from the Task. (We'll ignore exceptions here.)
Internal to your function, the network activity itself will also have taken the form of a standard-library Task, and our function will have made use of its `ContinueWith` method. Things can compose nicely in this way; `Task#ContinueWith` returns another Task.
(We needn't think about the particulars of threads too much here, but some thread clearly eventually marks that Task object as completed, so clearly some thread will be in a good position to 'notice' that it's time to act on that `ContinueWith` now. The continuation generally isn't guaranteed to run on the same thread as where we started. That's generally fine, with some notable exceptions.)
You might think that chain-invoking `ContinueWith` would get tedious, as you'd have to write a new function for each step of the way if we make use of several async operations - each continuation means writing another function to pass to `ContinueWith`, after all. Perhaps it would be more natural to just write one big function and have compiler handle the `ContinueWith` calls.
You'd be right. That's why they invented the `await` keyword, which is essentially just syntactic sugar around .Net's `ContinueWith` method. It also correctly handles exceptions, which would otherwise be error-prone, so it's generally best to avoid writing continuations manually.
There's more machinery at play here of course, but that seems like a good starting point.
Assorted related topics:
* If you use `ContinueWith` on a Task which is already completed, it can just stay on the same thread 'here and now' to run your code
* It's possible to produce already-completed Task objects. Rarely useful, but permitted.
* There's plenty going on with thread-pools and .Net 'contexts'
* The often-overlooked possibility of deadlocking if you aren't careful [0]
* None of this would make sense if we had to keep lots of background threads around to fire our continuations, but we don't [1]
* Going async is not the same thing as parallelising, but Tasks are great for managing parallelism too
* This stuff doesn't improve 'straight-line' performance, but it can greatly improve our scalability by avoiding blocking threads to wait on IO. (That is to say, we can better handle a high rate of requests, but our speed at handling a lone request on a quiet day, will be no better.)
I found this overview to be fairly digestible [2]
[0] https://blog.stephencleary.com/2012/07/dont-block-on-async-c...
[1] https://blog.stephencleary.com/2013/11/there-is-no-thread.ht...
[2] https://stackoverflow.com/a/39796872/
See also:
https://docs.microsoft.com/en-us/dotnet/standard/parallel-pr...
https://docs.microsoft.com/en-us/dotnet/api/system.threading...
Slight word of warning: `async/await` is more than just sugar in Rust, it also enables borrowing over awaits, which was previously not possible.
Async can be useful when more control over the details of execution is needed.
I've seen a lot of people try to manage complex programs by working with threads directly. Whatever they come up with is very unlikely to be as correct and reliable as the abstractions provided by the language. Even when they get it right, programs written with those techniques are difficult to modify without introducing new bugs.
Manual management of threads is becoming like manual management of memory -- it is discouraged by newer language features and you should only do if you really need to.
I thought Rust had other, better ways to create non-blocking code so I don't understand why to use async instead.
[0] https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...
In fact, Rust does have a great solution for nonblocking code: just use threads! Threads work great, they are very fast on Linux, and solutions such as goroutines are just implementations of threads in userland anyway. (The "what color is your function?" post fails to acknowledge that goroutines are just threads, which is one of my major issues with it.) People tell me that Rust services scale up to thousands of requests per second on Linux by just using 1:1 threads.
Async is there for those who want better performance than what threads/goroutines/etc. can provide. If you don't want to deal with two "colors" of functions, you don't have to! Just use threads.
Say you have 1000 threads. To handle a request each one needs to make 50ms of external or DB calls. In one second, each thread can handle 20 calls. So you can handle 20k requests/second with 1000 threads. But Rust is so fast it can serve 500k requests a second. So with regular threads, you need ~25,000 threads. The OS isn't going to like that.
With async you can run a single thread per core, with no concurrency limits. So you get your 500k requests without overhead. With fibers you just run 20k fibers which is a little bit of overhead but easy to do.
This is the core reason everyone is pushing async and fibers in fast languages. When you can push a ton of requests/second but each one has latency you can't control, regular threads will kneecap performance.
In "slow" languages like Python, Ruby, etc, async/fibers don't really matter because you can't handle enough requests to saturate a huge thread pool anyways.
But yes, eventually, for very heavy cases (more than what I would call "high") you will want async/await.
With 8k stack for each, you can easy have 10k-100k threads in a low-end system
"""Three more languages that don’t have this problem: Go, Lua, and Ruby.
Any guess what they have in common?
Threads. Or, more precisely: multiple independent callstacks that can be switched between. It isn’t strictly necessary for them to be operating system threads. Goroutines in Go, coroutines in Lua, and fibers in Ruby are perfectly adequate."""
What more do you need?
[0]: https://ziglang.org
The idea is that you can set the global "io_mode" mode to blocking, mixed or evented and I/O functions will switch their implementation accordingly. The type of the function will then, if I got that right, propagate up the call stack and turn functions that touch it transparently into either normal or async/awaitable funtions.
Nice way to avoid a bifurcation of the ecosystem into red/green functions. Its a bit magical maybe, any other trade-offs?
I mean, don’t you know at compile-time whether you want something to be async or not? If so, it should be handled by the type system, not by mutating a variable at runtime.
https://news.ycombinator.com/item?id=20676641
It's trivial to turn async into sync in Rust. You can use ".poll", "executor::block_on", et cetera.
Turning sync into async is harder in any language. Even Go with it's easy threading. That's a good argument to make async the default in libraries in Rust, but since async isn't stable yet, that would have been hard to do 5 years ago.
Rust had legitimate reasons for taking the approach that they did. One can agree that they made the correct decision without excusing and obscuring the consequential costs.
Five years ago Rust still had green threads. Literally every standard library I/O function was async, and the awaits were always written for you with no effort.
Its literally taken five years to get back to an alpha thats not as good, and we'll still have to wait for a new ecosystem to built on top of it. I know not everyone writes socket servers and so forcing the old model on everyone probably doesn't make sense long-term, but I still have to shake my head at comments like this.
D made a similar mistake by requiring GC/runtime from start and now even though they added ways to avoid it the ecosystem and the language design are "poisoned" by it an itmakeas it a very hard sell in some places where it could be sold as a C++ successor.
Because rust made the right choice in time it's now a contender in that space, if it chose to go down the runtime required/custom threading model route it would have much less practical appeal. If you can swallow runtime/threading abstraction overhead why not just bolt on a GC and use Go
The new I/O system is better in several ways. First, as you acknowledged, not everyone writes servers that need high scalability. M:N has no benefit for those users, and it severely complicates FFI. Second, async is faster than M:N because it compiles to a state machine: you don't have a bunch of big stacks around.
It also was constantly crashing and had weird semantic issues. I very much prefer the current state, even if I'm a bit sad that async/await has taken us so long.
Is it 0-cost abstraction? I mean, is `sync_read` will compile to the same code like `async_read.poll`? Because turning sync into async is kind of trivial as well: just spawn new thread for that sync block.
> What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better.
In that mind-set, it is completely okay that `sync_read` and `async_read.await` can totally compile to something different, as they abstract different things.
Boats has some more thoughts on this here: https://boats.gitlab.io/blog/post/zero-cost-abstractions/
- Create an epoll descriptor.
- Add my socket to that descriptor.
- Poll the descriptor for a readiness notification.
- Read the descriptor.
Those first three system calls weren't required in the synchronous version, and unless the read is large enough to overshadow them, they represent some additional cost. But that cost is required by the OS itself, not by Rust's abstractions.
Someone with more experience writing Mio code might want to jump in and correct me here though.
Sync is a rudiment of our close past. We use it when we need to shave off development costs.
well in most languages you can wrap sync into async. so it's not "hard". it's just harder to have NON blocking code. i.e. in c# there is a difference between:
`await Task.Run(() => Thread.Sleep(5000));`
and
`await Task.Delay(5000);`
both will wait for 5 seconds but one will waste cpu cycles while the other won't.
It is not easy to do in a cirrect and performant way. "async" doesn't mean "code that runs in another thread". You can have a single threaded runtime running async code (that's usually the case for javascript).
The "async-ness" is in those cases provided by the use of non-blocking primitives for IO, network etc. If a function is making a blocking call to the file system even if you make it async it will not help since the main thread will still be blocked on that system call.
The performance will also be quite different: waiting for data on 10000 sockets in a non-blocking way is quite different from having 10000 threads doing the same.
Elixir's Task module (in the stdlib):
future = Task.async(fn ->
do_something_here
end)
...do_other_things...
result = Task.await(future, timeout)
Mixing it with the Enum library makes concurrency dead-simple (got I a junior dev dispatching concurrent tasks in scripts with confidence), at the expense of an ugly nested double lambda. some_list_of_values
|> Enum.map(fn value ->
Task(fn -> do_something_with(value) end)
end)
|> Enum.map(&Task.await(&1, timeout))This is largely why Python async took so long to mature, because so much inbuilt functionality was making IO operations transparently using core sync impls that locked up any async executor.
This makes it a hell of a lot easier to reason about.
proc readLine(s: Socket | AsyncSocket): Future[string] {.multisync.} =
while true:
let c = await s.recv(1)
case c
of '\n':
return
else:
result.add(c)
This is equivalent to defining two `readLine` procedures, one performing synchronous IO and accepting a `Socket` and another performing asynchronous IO and accepting an `AsyncSocket`. It works very well in practice.The main challenges I see are around usability within the language design on how best to propagate and compose them.
[0] https://www.reddit.com/r/rust/comments/cjcwmu/is_there_inter...
No thanks.
As far as I understand, cooperative is far more efficient than preemptive, but unsuitable for poorly written or untrusted code.
I wish to learn and would really appreciate your assistance if you are willing to help.
Isn't the alternative WCiYF is proposing to allow the caller to treat any function asynchronously, while having no way to discern whether doing so might be counterproductive?
It's sometimes called "cold futures".
'async' exists because Python has that GIL bullshit and so Python programmers had to invent that fifth wheel of 'async programming'.
Programmers in other languages then got jealous because they, too, wanted a complex, unnecessary framework that pollutes the whole runtime and serves to differentiate regular programmers from 'rockstar' programmers.
And so async got fashionable and barely-literate coders now think async is magic performance dust that will automatically make your program run 1000% faster.
TL;DR - it's just fashion, give it five years and we'll be reading posts about how async sucks and that it's stupid legacy tech invented by bonehead dinosaurs.
C# introduced it in 5.0, which came out in August 2012. The Python proposal (PEP 3156) for an async library was posted in 2012, the proposal (PEP 492) for async/await syntax in 2015, and implemented in Python 3.4 and 3.5 respectively, I believe. So C# predates Python by about 3 years.
From what I can gather, Python was influenced by C#. But C# doesn't have a global lock, and that's not why it has async/await.
Edit: Added PEP reference.
But it's odd that they do not cite Tokio. I know this isn't an academic paper, but come on have some professional curtesy and discuss the contributions made in prior art.
Carl Lerche and the rest of the Tokio contributors deserve a citation.
I am curious if the number of threads is unbounded, or if they have a bounded set but accept deadlocks, or if there is a third option other than those two that I am unaware of.
https://github.com/async-rs/async-std/pulls?utf8=%E2%9C%93&q...
There is no true async I/O on most (if not all) current platforms - it's all threads, either in user space or in kernel space. Sometimes even deliberately, for example polling disk will give better latency compared to waiting for IRQ.
I can definitely imagine blocking happening while waiting for a worker to be available, though. Did you mean simply blocking instead of deadlock?
The same scenarios would lead to resource exhaustion if the thread pool wasn't bounded.
Also, anything from the tokio ecosystem like hyper would not work with async-std.
Edit: I originally had a first paragraph which was wrong. I mistakenly thought std::net::TcpListener is supposed to impl Read / Write.
It does implement AsyncRead and Write, because anything with `Read` and `Write` implements it: https://docs.rs/async-std/0.99.3/async_std/io/trait.Read.htm... (that's sadly a little backwards by rustdoc)
The problem is that tokio has their _own_ versions of the AsyncRead and Write traits.
Hyper can best be used with `async_std` through `surf`: https://github.com/rustasync/surf
>impl<T: AsyncRead + Unpin + ?Sized> Read for T {
That's saying that anything that impls futures::AsyncRead impls async_std::io::Read. async_std::net::TcpListener does not impl AsyncRead. (Compare with TcpStream and File which do.)
>Hyper can best be used with `async_std` through `surf`: https://github.com/rustasync/surf
Sure. You also don't need surf since you can directly use futures's compat executor wrapper around tokio's. The point is that you can't use stuff like hyper without the tokio executor being involved.
I beg to differ. If anything, Rust is often cited as being hard to read.
Rust code is littered with things like |_|, (|&(&x, _), &mut, &'a and Result<(), Box<dyn std::error::Error + Send + Sync>>.
It's anything but easily readable.
So we need Rust for younger generations.
This is bunk. Simply run this search[1] and behold the stream of Rust related submissions that get no play at all; zero comments and no more than one or two up votes. These instances of highly ranked rust stories are actually the exception; no more than one or two a week typically. The rest of the Rust stuff is seen by almost no one.
[1] https://hn.algolia.com/?query=rust&sort=byDate&prefix&page=1...
Features like Haskell—destructuring bind, useful type system.
Performance like C, including no GC.
Makes it a good option when reliability and performance matter (think web browser, database or anything at the OS level).
The thing I like in Go is that I don’t have to worry about that, it’s all automatic.
It's not Go, but we know what people like about Go. <3
Go is such a joy to work with.
It exports stdlib types (like io::Error) where appropriate so that libraries working with these can stay compatible, so `no_std` is not really an option.
The underlying library (async-task) is essentially core + liballoc, just no one made the effort to spell that out, yet.
Excellent, good to know!
It would be nice if you could provide your own sys crate so you could even use some of std on an embedded device. If you had say an RTC you could make time related calls work, maybe you'd wire networking to smoltcp etc. Currently you could do that - maybe - but you'd have to modify the Rust standard library.
But that plan is severely understaffed, we go so much else to do.