930 points · by steveklabnik · 10y ago · 337 comments
This allows one to express concurrency in a natural way not prone to the typical errors of problems of this nature, with no runtime overhead, while competing with C in terms of the constraints of the runtime.
Big kudos to Aaron Turon and Alex Crichton. You guys knocked it out of the park.
Deferred based approach has been a round for many years. I experienced it by using Twisted (Python framework) for 5 or so years. And early on it was great However when we switched to using green threads, the logic and amount of code was greatly simplified.
So wondering if Rust provides any ability to add that kind of an N:M threading approach. Perhaps via an extension, macro or some other mechanism.
Note that in C, it being C such things can be done with some low level trickery. Here is a library that attempt that:
And there were a few others before, but none have taken off enough to become mainstream.
I don't want M:N threading as Go implements it. It's a big loss of performance for marginal benefit over futures. In particular the libmill approach was tried in Rust and the results were far worse than 1:1.
However, assuming this takes off I would like to see async/await style syntactic sugar over futures down the road to make it easier to write code that looks blocking but actually isn't. Crucially, this sugar would maintain the zero-cost nature of futures. With that approach, we'd have the ergonomics of languages like Erlang and Go without the significant performance tax associated with M:N.
As someone who writes code for enterpricey businesses doing a lot of I/O bound stuff, golang style M:N threading is a godsend over Java's standard library, and other common platforms in that space. Being able to express your code in a sequential manor and still gain the performance offered by implicit fiber,goroutine,w/e scheduling is pretty awesome. With futures, there's still some language semantic overhead from the point of view of the developer.
In my problem space, M:N threading is simply worth it. And if I need anything better performing, I can still switch to C for specific use cases.
You don't gain as much performance. On Linux, you don't actually gain that much if anything over 1:1 threading. Most of the benefits of goroutines actually comes from the small stacks, which don't have anything to do with M:N and 1:1 to begin with—they're a feature of GC.
As the blog post states, our end goal is to achieve the ergonomics of Go-style M:N without sacrificing nginx levels of performance. With this futures library, we've established the foundations. It would make no sense to give up before even trying.
> And if I need anything better performing, I can still switch to C for specific use cases.
Why would you write networking code in C in 2016, when there are better alternatives available (like this one)?
Rust's philosophy is to have both performance and ergonomics. It rejects the idea that optimal performance requires a cumbersome programming model. I'm not about to give up on that.
It maybe sounds like you should just use Go, which (as you point out) makes exactly those tradeoffs. I think Rust is aiming for a different market segment, with customers that want to make a different set of tradeoffs. Seems ideal to have both options. In particular, I don't think switching to C will ever be something Rust will want to require of its users.
So use go and switch to rust for specific use cases.
Yes! That is basically what I am after.
Currently using Erlang so having to give up cheap isolated processes and message passing to do concurrency would be hard. But I understand that is a different level of abstraction as well (a VM, multi-machine clusters, etc vs almost raw C speed).
But in general bringing Rust and Erlang together seems like a swell idea. Both are focused on safety, which I like. Been keeping my eye on https://github.com/hansihe/Rustler
Would a Scala-style 'for' comprehension achieve the same thing while also being more generally applicable? Scala achieves this by using instance methods 'map', 'flatMap' and 'withFilter'. Personally I think Rust should just lift the sugar wholesale :-)
Is this new approach different because instead of stack frames you just have dynamically allocated callback state?
In the M:N approach you have to allocate stack space for each goroutine that you spawn. This requires that you either know the size of the stack up front (generally not possible without being conservative and requesting a large allocation) or that you start small and grow (resulting in a lot of memory traffic and pauses in the growth case, and much harder to do in C).
By contrast, with the zero-cost futures approach we statically know exactly how much per-goroutine size we will ever need, and we can allocate precisely that amount. Furthermore, we only save the data that's absolutely needed across blocking calls. This results in much smaller per-connection state, and as a result it's quicker to allocate.
It's the difference between static and dynamic control flow. Full M:N requires us to give up static knowledge of what a goroutine will do and try to do the best we can at runtime. With futures, we have a lot more static knowledge, and as a result we can optimize more aggressively.
Regarding stack vs. dynamically allocated state (in a future) I'm not convinced what's better. Yes, the allocated stack most likely has an overhead. But at least the data will be stored there in linear fashion and accessing the state will be super cheap once the stack is loaded. In case of futures that hold dynamically allocated data the state might be spread over much more memory locations, so it might be slower to access. I however haven't any more scientific data on this.
In my real-world applications I'm getting about the same performance from a Go based and a boost asio (uses no futures but dynamically allocated callback closures for storing state) networking application. However the programming style is completely different.
Can you quantify the "performance tax associated with M:N"?
When I look at the benchmark of your minihttp vs Go fasthttp, Rust is supposed to be 3x time faster without any GC and yet minihttp pulls 2M req/sec VS 1.5 for Go which is a small margin when you know how Go works and is GC.
I explain in this sibling comment: https://news.ycombinator.com/item?id=12271194
> Do you have any numbers about this implementation?
See the blog post.
My brain read that as "ergolangmics"
John Reppy's CML seems like a much better toolbox which gets composability without pretension. Vesa Karvonen (whom I understand has worked on the MLTon compiler) has offered an excellent delivery in Hopac for C# and F# complete with a slew of combinators: https://github.com/Hopac/Hopac
I'm not aware of anyone offering an alternative superior to an informal CSP yet which seems to be the reason why Go and Clojure have picked it as well for their concurrency model.
See David Nolen's excellent blog posts on the matter:
http://swannodette.github.io/2013/07/12/communicating-sequen... http://swannodette.github.io/2013/08/17/comparative
Munificent's http://journal.stuffwithstuff.com/2015/02/01/what-color-is-y... expresses the problem eloquently.
None of that means you're wrong about async making "a lot more sense for the language", though.
While i agree with the tradeoff made by rust (although i think the approach used by C++ coroutine is better), i don't think that having async/await syntax give you "most" of the ergonomics of the Go M:N model .
The main advantage of the go model is that both asynchronous and synchronous operations are identical, with async/await you still need to model the async operation and the sync operation with different types. Not having to decide(and design) upfront which part of your computation is async and which is not is what makes go so attractives
What about Quasar [0] on the JVM?
Rust doesn't natively supply anything like green threads, as they have too heavy of requirements. But there are librarys that can implement them, since Rust is so low-level: https://crates.io/crates/mioco as an example.
You get a strange sense however when playing with Hopac (which btw has an analog sugar to F#'s async which works just fine) and going through the content in Reppy's book that the model is strictly more composable. I'd invite you to try it although I don't have a sense for the C# combinators.
I’ve claimed a few times that our futures library provides a zero-cost abstraction, in that it compiles to something very close to the state machine code you’d write by hand. To make that a bit more concrete:
- None of the future combinators impose any allocation. When we do things like chain uses of and_then, not only are we not allocating, we are in fact building up a big enum that represents the state machine. (There is one allocation needed per “task”, which usually works out to one per connection.)
- When an event arrives, only one dynamic dispatch is required.
- There are essentially no imposed synchronization costs; if you want to associate data that lives on your event loop and access it in a single-threaded way from futures, we give you the tools to do so.
This sounds quite badass and awesome. I'm not sure what other language implementations take this approach, but this is clearly an extremely beautiful, powerful, and novel (to me at least!) concept. Before reading this, I thought rust was great. This takes it to the next level, though.
> ...we’ve added a comparison of minihttp against a directly-coded state machine version in Rust. The two are within 0.3% of each other.
How are are handling errors ? - One Error state with the context ?
https://doc.rust-lang.org/book/error-handling.html
Suffice it to say, similar magic tricks have already been at work to make handling errors not soak up a lot of space, and it'd work well with something like this, I think.
Rust takes an approach with generic functions called monomorphization which means that we generate a new version of each function for each set of generics it's instantiated with. This means that a future of a String will generate entirely different code from a future of an integer. This allows generics to be a zero cost abstraction because code is optimized as if you had substituted all the generics by hand.
Putting all that together, highly generic programs will generally trend towards higher compile times. With all the generics in play, there tends to be a lot of monomorphization which causes quite a lot of LLVM IR to get generated.
As with many aspects of Rust, however, you have a choice! Rust supports what we call "trait objects" which is a way to take a future and put it behind an allocation with a vtable (virtual dispatch). This forces the compiler to generate code immediately when a trait object is created, rather than down the line when something is monomorphized.
Put another way, you've got control over compile times if you're using futures. If you're taking a future generically and that takes too long to compile, you can instead take a trait object (or quickly convert it to a trait object). This will help cut down on the amount of code getting monomorphized.
So in general futures shouldn't make compilation worse. You'll have a choice between performance (no boxes) and compile times (boxing) occasionally, but that's basically already the case of what happens in Rust today.
Unlike C++ templates, Rust enforces a single definition with uniform semantics, for a generic type/function (specialization going through the existing trait static dispatch mechanism), so we can take advantage of that to reduce compile times.
It's interesting that this is seen as significant here. Are we dealing with much shorter timescales, or just being eager to optimise everything?
However, now that we have MIR we can optimize this on the Rust side first, before the type info has been lost. This was one of the reasons MIR was added :)
Maybe you mean LLVM is very low-level and thus it sees everything in the abstractions, which obviously takes time to sort through (and is especially wasteful to do multiple times for different monomorphisations). Thus, using MIR to optimise at a higher level can simplify code more efficiently before it hits LLVM.
fn get_row(id: i32) -> impl Future<Item = Row>;
That return type looks odd to me. What does it mean to return an "impl", and is that a new feature in rust, or just something advanced that I missed in my exploration before?- http://aturon.github.io/blog/2015/09/28/impl-trait/ - https://github.com/rust-lang/rfcs/pull/1522
This feature allows you to return any struct that implements the trait, without having to type the name of the struct (which can sometimes be quite big). It also means that clients only know what traits are implemented; the concrete type is invisible to them. The above links have a bunch more detail.
(And this feature is set to land in nightly Rust very soon! Shoutout to eddyb :)
There may or may not be some extensions (like storing them in fields of structs) in the future.
Note that Rust supported existentials before too, in the form of trait objects. But this was only possible behind a pointer and using virtual dispatch, so the performance story wasn't perfect. The impl Trait syntax is supported through monomorphization.
fn did_too_many_chains() -> Chain<Map<'a, (int, u8), u16, Enumerate<Filter<'a, u8, vec::MoveItems<u8>>>>, SkipWhile<'a, u16, Map<'a, &u16, u16, slice::Items<u16>>>>
Now, you can write: fn did_too_many_chains() -> impl Iterator
and be done with it.https://github.com/rust-lang/rfcs/blob/master/text/1522-cons... is an explanation of the feature in detail, but it boils down to "I will return you some kind of thing that implements the Future trait, but I'm not telling you exactly what it is."
All of Rust's standard collection and smaht pointer types are written in pure Rust and have relatively complex variance behaviour.
https://github.com/rust-lang/rfcs/blob/master/text/1522-cons...
I notice it's consistent with the standard `Iterator<Item = ...>`, but why is Iterator like that?
The first observation one can make - which is not mentioned anywhere in the article - is that the composition of futures here can be understood as a monadic composition. This by itself gives a big hint why this interface is so powerful. Second is that this library could be understood as an implementation of process and process combination from pi-calculus [1] - sequential combination, joining, selection, etc - so it could be formalized using its process algebra.
From the practical side, one example of a mature library that implements similar concepts is the LWT [2] library for OCaml, which has the same idea of deferred computation, joining and sequencing, but calls the computations "lightweight threads". One could also argue about naming in this case, but it seem to reflect a better the idea of independent "processes" that are combined on the same address space.
Finally, as much as these concepts of futures and processes look similar on the surface, they each have their own properties - so it's always good to consider what better fits the model. By looking at the research and at other similar solutions, one can make more informed choices and have a better idea of what to expect from the implementation.
1 - Isn't the state machine approach the same as C#/.net async/await is using ? But the with the added convenience of the syntactic sugar ?
2 - no allocation : , does'nt the lambda closure need to be allocated somewhere ?
3 - I would have love some comparison (booth performance wise and on theory) with C++ up comming coroutine work, from my understand the C++ approach is even more efficient in term of context switching and have the advantage of even less allocation.
Similar in principle, but the implementation is different. Tasks in C# are more of an OO style instead of a FP style where they turn into an enum (sum type, if you want to get theoretical).
> 2 - no allocation : , does'nt the lambda closure need to be allocated somewhere ?
No, not in Rust (or in C++).
> from my understand the C++ approach is even more efficient in term of context switching and have the advantage of even less allocation.
No, you're asserting this without understanding Rust. It's not possible to get less than zero allocation.
In practice, you build up a really big combined future on the stack, which has all of the space needed for any state in its state machine, and then when the future is fired off (in a task -- one per connection), that entire thing is moved into the heap in one shot. Thus, generally, you do one big allocation up front per connection -- exactly the same as you'd do when writing state machines by hand.
The follow up posts will go into much more detail on this point :)
If you need to hold onto data accessed from multiple locations, you'd need to use Rc<T> instead of keeping that data on the stack, which is closer to GC'd languages (and pretty similar to Swift, IIUC, except Rust is more explicit).
> There are essentially no imposed synchronization costs; if you want
> to associate data that lives on your event loop and access it in a
> single-threaded way from futures, we give you the tools to do so.The closest things in the standard to these rust futures, is of course std::future, which currently is very limited as it even lacks chaining and composition. The Concurrency TR (which eventually will be added to the standard, but sadly not for C++17) does provide these features (and more); multiple implementations have been are available for some time (boost, HPX, Folly, and some compiler vendors).
The issues with std::future is that is far from zero cost, as it requires allocation (the control block is dynamically allocated), type erasure (the callback type is not part of the future) and synchronisation (as the promise can be fulfilled from another thread). Efficient implementations of std::future are possible but will never be as fast as what is shown in this rust library.
On the other hand the SeaStar C++ library (I'm in no way involved, just a fan) already provides pretty much the same zero cost futures with a very similar implementation as it doesn't try to follow the standard design.
You seems familiar with the C++ committee, do you know a good way to track a feature one is interested in ? I kinda lost track of the coroutine proposal after the 4 revision or Gor paper.
By the beside Visual studio, any other compiler has a working implementation of the current draft ?
I'm not part of the committee nor I attend meetings, but I follow the papers and the public online discussions.
The one time that you do tend to see closures get boxed is when returning them, because you can't write out their type. In the future you'll be able to get around that by using the `impl Trait` syntax mentioned in the post (https://github.com/rust-lang/rfcs/pull/1522).
2. Closures are on the stack, not the heap, by default, in Rust. If you don't see a Box, they're not heap allocated.
3. I agree!
I expect it is embedded in the state machine structure. In Rust (and C++) lambdas/closures are "value types".
If you stick to the raw lambdas, however, the compiler knows the size and doesn't need to use the heap. Only problem is that their type can't be named. In C++, you can work around this with auto.
Without getting too much into it, Rust has a similar distinction between raw lambdas and Box<Fn(...)>. This library uses the former.
futures-minihttp(singlethread):
$ wrk -c 100 -t 2 -d 20 http://127.0.0.1:8080/plaintext
Running 20s test @ http://127.0.0.1:8080/plaintext
2 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 823.09us 449.37us 20.98ms 98.69%
Req/Sec 62.15k 10.51k 105.24k 48.63%
2479035 requests in 20.10s, 340.44MB read
Requests/sec: 123335.77
Transfer/sec: 16.94MB
lwan(singlethread): $ wrk -c 100 -t 2 -d 20 http://127.0.0.1:8080/
Running 20s test @ http://127.0.0.1:8080/
2 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 596.45us 573.31us 24.46ms 99.33%
Req/Sec 86.17k 13.15k 119.71k 76.00%
3429720 requests in 20.01s, 624.73MB read
Requests/sec: 171404.15
Transfer/sec: 31.22MB
For lwan i use http server example from lwan.ws main page.As you can see in this example C http server much faster than simple http Rust server.
* futures-minihttp release build
* lwan -O3
[1]: http://reddit.com/r/rust/comments/4x8jqt/zerocost_futures_in...
$ wrk -c 100 -t 2 -d 20 http://127.0.0.1:8080/plaintext
Running 20s test @ http://127.0.0.1:8080/plaintext
2 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 633.87us 808.22us 24.66ms 98.41%
Req/Sec 86.72k 4.84k 94.90k 85.75%
3452383 requests in 20.01s, 424.73MB read
Requests/sec: 172546.21
Transfer/sec: 21.23MB
lwan(2 threads): $ wrk -c 100 -t 2 -d 20 http://127.0.0.1:8080/
Running 20s test @ http://127.0.0.1:8080/
2 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 375.26us 618.54us 20.60ms 98.21%
Req/Sec 116.82k 5.56k 124.07k 92.25%
4647906 requests in 20.00s, 846.62MB read
Requests/sec: 232339.90
Transfer/sec: 42.32MBAll this "futures" stuff strongly favors the main path over any other paths. You can't loop, retry, or easily branch on an error, other than bailing out. It's really a weird syntax for describing a limited type of state machine.
I'm not saying it's good or bad, but it seems a bit tortured.
Why do you think Rust has cruft anyway? It has a lot of typesystem features, yes, but this is no different from languages like Haskell. These features work together nicely and are useful. C++ has lots of features which for better or for worse have been hacked in to the language (can't be made an organic part of the language because backcompat). This is not the case with Rust (or D, which is to me a cruft-less organically-designed C++)
The bothersome thing is that the control structures of the language are hidden under object-specific functions. "Things really start getting interesting with futures when you combine them. There are endless ways of doing so." I'd rather have "there's only one way to do it", as in Python, rather than "endless ways of doing so". That usually leads to code that's hard to read and debug. As in "how did control get there?". At least in traditional code, you can see control flow easily. Adding an user-definable level of abstraction hides that.
uh, no, I've rarely seen adaptors like and_then being used with side effects (folks use regular loops if they want that). Rust doesn't have a strict notion of purity, but that doesn't mean that most rust code isn't pure.
There's nothing wrong with having lots of adaptors scattered around the code, either. It's not less readable, it's just different.
> There are endless ways of doing so." I'd rather have "there's only one way to do it", as in Python
Uh, "there are endless ways of combining future adaptors", not "there are endless ways of solving a problem". Each combination of adaptors solves a different problem (mostly).
> That usually leads to code that's hard to read and debug
This is async code. This has always been hard to read and debug. Futures make the control flow more explicit, if anything (especially if you have async and await), because the flow is now in one place, at least. Grokking manual event loop code is much more annoying.
Sure, the async argument doesn't apply to regular iterators and Option. However, these "object specific functions" are not object specific. All futures have the same adaptors. All iterators have the same adaptors. The only special objects with their own set of such methods are Result and Option. These share the names of the methods, and these are used often enough to justify it. There aren't that many of them either, so this really isn't that big a deal. You just need to know what each of this small number of methods does. It only hides control flow if you're not aware of these methods, which is a state of mind that goes away quickly after the first few rust programs.
Besides, because of the closures it's pretty obvious that some tweaking of control flow is happening, so it isn't hidden. You can check the docs for that function to know exactly what the tweaking is.
I also don't know what you mean by "traditional code", this pattern is exceedingly common in languages which aren't C or C++.
You can do all of that.
As for repeating something multiple times, you would either repeat the chain 10 times or write your own future combinator. Probably writing a custom future combinator would make the most sense here; actually, such a thing ought to be built-in to futures.rs.
I will be the first to admit that Rust is not perfect, but that adjective does not come to mind. I am of course incredibly biased.
.map(|row| { json::encode(row) })
.map(|val| some_new_value(val))
Over .map(json::encode)
.map(some_new_value)
Is the explicit extra layer of lambda generally prefered in Rust over just passing the functions?Debugging promises/deferreds in other languages has given me nightmares, compare with erlang/golang debugging where you get a simple stacktrace.
Does this provide some nice way of debugging complex future chains? Are there plans towards making it super easy to debug?
Cheers!
Debugging promises in JavaScript is very easy at the moment.
I'm not generally a big fan of measuring the "ping time" response for web servers, but in this case I believe it is justified since we really are trying to establish that this future library is very fast. I fear, based on experience, that some developers well be looking at this and will sit there trying to choose fasthttp vs. rapidoid vs. minihttp based on this one graph, without considering what they really mean. Overhead-per-request I think makes it more clear that for the vast, vast majority of purposes, all of these, including Go and Node, are "way way faster than your code", and unless you know you're building a server where you seriously need to answer an API call at several hundred thousand responses per second, all of these are "fast enough" and the real criteria for choosing should be "everything else".
(One last edit... remember, it's "milli/micro/nano". Micro seems to be forgotten since it seems like many things that we care about fit into nano- or milli-. It's quite a challenge in the web world to get your request out in under a millisecond usually, so .040 milliseconds added as HTTP overhead is rarely the problem.)
Sure, but it's not the responsibility of this blog post to protect bad/lazy engineers from themselves.
To me, Go feels like C-but-some-things-are-GCd, which Java is not. The explicit sharing annotations in Go means that it's super easy for it to not put most of the things on the GC heap, and it's super easy for me, the programmer, to see what's not being put on the GC heap. Whenever I've debugged Go code this been validated.
But yes, it's not as clear cut. I ignored the threading runtime being a factor, and ignored that Java has a better GC (though it GCs more things).
I also ignored JIT as steve pointed out to me in irc.
So yeah, there could be language reasons behind the benchmark order too. Worth investigating though, I'm sure the folks using fasthttp would love a perf boost :)
https://www.techempower.com/benchmarks/#section=data-r12&hw=...
Also, how do you debug code that's hung or taking too long? It might be useful to get a list of all the jobs (incomplete Futures) that are currently running, much like running 'ps'.
In terms of debugging, there's not infrastructure currently, but the kind of thing you're talking about should be easy to add!
The challenge of these state machine codegen abstractions is not performance. It's making source-facing debuggers do the right thing and handle errors in a way that doesn't break the illusion that the code running is the code in source.
If you can match the degree of support C# has for error handling, you'll be in an amazing place.
Like other kinds of debugging info, you might also want a way to strip out the job names in a production build.
Extra tests for more complex stuff would be great.
About the naming though, I was a little disappointed. Out of future, deferred, and promise, "promise" is the better term. The two others imply that something will happen later which is misleading because it's fine to have promises stick around long after they're fulfilled.
But, if you want C++, check the data from the original benchmark which was linked: https://www.techempower.com/benchmarks/#section=data-r12&hw=... . The Java one is slightly faster than the C++ one (more like "just as fast", since the difference is tiny). And there are 7 more java libs (half of them with recognizable names) before the next one (which I've never heard of), which underlines my point about this being more common in Java than C/++.
The benchmark wasn't shown to prove that Rust is the fastest language in the universe. It was shown to prove that the Rust futures implementation is competitive with the others in use today, ones which people would recognize.
One quibble I have with this post is that it talks about futures as a zero-cost abstraction. That might be true (or close to true) from a performance perspective, but in my (admittedly inexperienced) opinion, it seems to have a significant ergonomic cost that is not accounted for.
While futures help us deal with multi-threaded coordination of data from multiple sources, that overhead isn't necessary for situations where you're running in a single thread dedicated to doing IO operations.
Dealing with futures in your code is not non-trivial. Browsing through the futures version of the HTTP server, I had a hard time following along:
https://github.com/alexcrichton/futures-rs/blob/master/futur...
And it requires a bunch of helper code to go with it:
https://github.com/alexcrichton/futures-rs/blob/master/futur...
The blog post mentions Tokio, another high-level abstraction on top of mio (by the same author). Because it doesn't require the futures abstraction from top-to-bottom, it offers similar (maybe even a little better) performance with what, to my eyes, is far simpler code:
https://github.com/tokio-rs/tokio-minihttp/blob/master/src/l...
I'm still learning Rust and spend most of my time in JavaScript. The analogy I'd use is: imagine if in the Node programming model, every API required you to use JS Promises, even at the very lowest level. Even if you could reduce the cost of creating new Promise objects, interacting with them over simple values could make the code you write more verbose. In Rust, that problem is exacerbated by the much stricter type system and the fact that you have to do cross-thread coordination.
I'm a total beginner to systems programming, and a lot of this stuff is above my pay grade. However this shakes out in the community, I'm very happy to see Rust on the way to becoming the fastest, most productive way to write high-performance web services.
I'm a little confused about the snippet you're pointing out. It's not actually using futures at all! In fact, that code is just part of setting up threads for the server. The reason it's more complicated than the version in Tokio is that minihttp supports multiple event loop threads (which gives some performance benefits), and this code is handling that setup.
At a broader level, Tokio's services -- the main thing users write -- are based on futures, in exactly the same way as minihttp. So for people writing actual servers, the ergonomics should be the same.
Now, stepping back, it's definitely true that ergonomics are a cost to be aware of, and it's one we've thought carefully about in the design of futures. We've had a lot of experience and success in Rust with iterators, which share a lot of the same API design philosophy.
That said, I do anticipate that over time we'll want to layer sugar on top of futures. As I mention a couple times in the blog post, async/await (or something like it) is the obvious way to do it, and there's plenty of prior art. But I think we should walk before we run -- let's make sure we've got the core abstraction right, and then we can sprinkle some sugar where it's needed.
Your application work - computation logic/business rules, should be decoupled from the type of worker.
The worker can be - blocking or non-blocking - Futures/Continuations/Co-routines.
Awesome stuff btw, love the iterator inspiration.
I'd recommend a beta compiler for now though to compile some of the examples. There's a bug in the stable compiler which causes them to take up to 8x longer to compile, but beta/nightly are both speedy!
Serious Kudos, it feels like a lot of the promises of Rust are really paying off here.
Right now, nothing happens with the panic after it's caught, but we want to add hooks for doing something with it. Coming soon!
So, this will work on stable. It was presented that way to not get into the whole details about the whole impl trait shenanigans in general.
Would be great if functions could be written in a general way for both IO models and users could select the implementation at their convenience.
> no sane way to intermix them.
My understanding is, the idea is to put the blocking stuff in a threadpool with https://github.com/alexcrichton/futures-rs/tree/master/futur...Maybe you use one library that is futures-based and one that isn't. Maybe the library you use is mostly non-blocking except for one use of sleep() or another esotorically blocking call. It's just annoying and prone to error. Most people may not even be aware of the subtly blocking nature of the code they use in their futures-based project.
This is what I mean by having two different languages. Libraries written for one aren't always/simply compatible with the other. You'll have a growing community of nominally "futures-based" rust libraries too.
This is why people use Go or Erlang. It just removes the need to have to think about this. Not saying they are generally better than Rust, and some Rust people may even like having a futures-based sublanguage, but I suspect most programmers will be loathe to have to deal with the extra mental tax.
So just like if you use cgo. You can't get away from having to deal with the issue entirely; the most you can do is to punt it to the FFI layer. There is the question of how much of the community is using blocking vs. nonblocking I/O, to be sure, but Go has a version of that too: how much of the community is using cgo vs. how much of the community is writing in pure Go.
> This is what I mean by having two different languages.
Calling them "two different languages" is a huge exaggeration. You simply block or switch to a thread pool: it's very easy.
> I suspect most programmers will be loathe to have to deal with the extra mental tax.
I like having the low-level control over blocking vs. not, especially in situations where I can't use async I/O everywhere (for example, my work on Servo). In fact, it's essential.
Ultimately this is going to come down to "you should be willing to pay a performance and control tax for a more ergonomic model" vs. "you shouldn't give up performance and control for a small amount of ergonomics". Yes, there is a tradeoff here. That's fine. Taking Go's side of the tradeoff would make Rust unusable for my domain, and for many others (which is why M:N was the most controversial issue ever in the Rust community, with most of the community demanding it to be removed, while in Go nobody questions it). Some people may not want Rust's side of the tradeoff, and that's fine too.
We tried this with a compile-time switch between 1:1 and M:N threading in earlier versions of Rust and the results pleased nobody. It was slow, complex, and unwieldy.
What I'm referring to here is the same futures method under the hood but transparent to the user.
It's also my understanding that there were unrelated engineering constraints that caused it to be unwieldy, such as binary size. I believe it's possible to provide an alternative runtime without it necessarily affecting the main configuration or limited environments like embedded devices.
CPS transforming the entire program is possible in theory, but if you want the same zero-cost behavior you will run into the same issues I outlined elsewhere: higher order control flow analysis will be necessary, and it will fall down a lot.
I don't. :)
Futures are a very generic abstraction that doesn't really favor any approach any more than, say, iterators do.
Seeing articles like this makes me feel like a circle has finally been closed.
How convenient. I've been exploring/learning Rust, and writing a simple echo server and comparing it to a reference version I've written in Perl is my first semi-trivial program I wanted to do to compare.
Wouldn't it be possible to add coroutines to Rust instead?
Say we make a Future<Int> and then chain `.map(|x| x+1)` on a dynamic number of times (N). Presumably this requires storing at least N function pointers.
How can we store these N function pointers with zero cost? If it only takes one allocation, where does the N-1 future store its function pointers?
If you don't need the dynamic behaviour, the library is a zero-cost abstraction, by statically encoding all the pieces at the type level: like Rust's iterators, each combinator function returns a new future type that contains all information about its construction and operations. To add to this, a closure in Rust is not a function pointer, each one a specialized struct containing exactly the captures, and thus this all gets put into the type information too, and everything can be be inlined together into a single pipeline.
However, if you are dynamically constructing the future you'll have to opt-in to a uniform representation for the parts (i.e. erase the type information about the different constructions). This does indeed require allocating and storing pointers, but AFAICT this is required in any implementation, i.e. this library imposes no/little extra overhead over the optimal hand-written implementation.
Furthermore, the static and dynamic parts can work together: if you have parts that are statically known, these can be constructed as a single static type (with no function pointers or allocations), and then boxed up into a dynamic future as a whole unit, which can then also form part of other static chains, meaning allocations and dynamic calls only need to happen when absolutely necessary.
Say I sometimes have an outstanding asynchronous operation, i.e. validating some text in a document. I want to represent this by storing a Future representing this operation:
struct Document {
text:String,
validating: Option<Future<Bool>>
};
It seems like there's a problem: in order to have a struct of this type, we need to have the type of the Future, but the only way to have the type of the Future is to create the Future (and here we have None).It this struct possible? How would I initialize it with {"foo", None}?
I'm not an expert but one of the ongoing dicussions in the impl Trait RFC is where the construct can show up. The preliminary version can only appear as a return type from a function where the compiler can always determine the exact details at compile time depending on the chain of calls. I believe typing out the entire type of the future in the struct would work but, again, I only somewhat know my way around the language.
Each time you call `.map` it statically produces a different type, similar to how iterators work. So you can't actually do that—unless you box the trait, producing an allocation chain.
Of course, in the real world you'd probably not write it that way, and you'd maintain a counter and do the add in one go, which results in a static state machine.
Basically
`MyFuture.map(x)` => `Map<MyFuture, X>`
`MyFuture.map(x).map(y)` => `Map<Map<MyFuture, X>, Y>`
This is obviously disgusting to expose to users, which is one of the reasons this post uses the `impl Trait` syntax to cover it up and say "well it's something with the right interface, the compiler knows it (so no need to do dynamic dispatch), don't worry about it".
let fut = Future<void>::new();
let v = vec![file, file2, file3];
for file in v.into_iter() {
fut = fut.and_then(file.close());
}
Is this possible with this API, or would the assignment to `fut` break because we now have a different type?With traditional Futures I'd expect this to look like a sort of linked-list of closures (definitely lots of allocation). What does it end up looking like under the hood with zero-cost Rust futures?
Similar to other languages, you'd have to allocate. In rust, it would probably look like:
let mut fut: Box<Future<()>> = Box::new(Future<()>::new());
and then fut = Box::new(fut.and_then(|| file.close()));However, the library does provide various abstractions that can abbreviate certain patterns and do them more efficiently than otherwise, e.g. http://alexcrichton.com/futures-rs/futures/fn.collect.html for this case.
Like this:
fut = v.into_iter().map(|file| file.close()).into_future(); > C++ implementations obey the zero-overhead principle: What
> you don’t use, you don’t pay for [Stroustrup, 1994]. And
> further: What you do use, you couldn’t hand code any better.
>
> – Stroustrup
So, in this context, the idea is that if you hand-rolled your own state machine, you should see no difference than using this library. And, we measured: the overhead in a benchmark comparing the two was 0.3%, that's three tenths of one percent.So the title/TFA is about "futures" (in the sense of my link) that have "zero cost" (in the sense of steveklabnik's comment).
Why can't we have some syntactic sugar to get rid of .unwrap()?
It's not yet clear if said sugar will support Option; that's one of the reasons it's not stable yet.
Feel free to post off-topic questions on https://users.rust-lang.org/ any time!
https://doc.rust-lang.org/book/error-handling.html#the-try-m...