14 ms·
Fearless concurrency with Rust
- deleted 12y ago[deleted]
- rntz 12y agoThis post observes that > the same tools that make Rust safe also help you tackle concurrency head-on. The tools that make Rust safe, in this instance, being its ownership type system. Why on earth should that be the case? Why would ownership types make concurrency easier? The post gives plenty of in-depth answers to this question, but to my mind it misses the bigger picture. The big-picture reason why ownership types and concurrency match so well is the Curry-Howard correspondence. Ownership types are known as linear[1] types in the PL theory literature. Linear types are so-called because they correspond to linear logic, a logic sometimes described as "the logic of resources" rather than "a logic of truth". In linear logic, instead of reasoning about eternal truths like "1 + 1 = 2", you reason about resources, like "I have an apple and a banana". If you also happen to know that "from an apple, I can make applesauce", then linear logic lets you reason that you can obtain the state "I have applesauce, and a banana" (but no longer an apple). However! Linear logic has another interpretation, a Curry-Howard interpretation. You can also view it as a type system for a concurrent language based on message-passing, where your types describe the protocols message-channels obey. "I have an apple and a banana" corresponds to a channel which will first produce an apple, then a banana, then close. This is known as the session-types interpretation[2]. At first glance it may seem that this interpretation of linear logic and Rust's interpretation are unconnected. I doubt it; in logic, everything connects to everything else. It's no coincidence, for example, that ownership (linearity) is what you need in order to send mutable values across a channel without copying. There is a deeper structure waiting here to be discovered, and I for one am deeply excited about it. [1] In Rust's case, technically they are affine types. An affine type is a linear type whose values can be freely dropped, i.e. deallocated. [2] Session types have been around for a long time, but only fairly recently was the connection to linear logic discovered. Links/papers on session types: 1."Propositions as Sessions" by Wadler (http://homepages.inf.ed.ac.uk/wadler/papers/propositions-as-sessions/propositions-as-sessions-jfp.pdf http://homepages.inf.ed.ac.uk/wadler/papers/propositions-as-...) 2. Caíres and Pfenning, "Session types as intuitionistic linear propositions" (http://www.cs.cmu.edu/~fp/papers/concur10.pdf http://www.cs.cmu.edu/~fp/papers/concur10.pdf) 3. Pfenning's published works page (http://www.cs.cmu.edu/~fp/publications.html http://www.cs.cmu.edu/~fp/publications.html).
- jallmann 12y agoFantastic explanation of linear types. Another (experimental) language that uses linear types to facilitate concurrency/parallelism is LinearML: https://github.com/pikatchu/LinearML https://github.com/pikatchu/LinearML
- doublec 12y agoATS is another language that uses linear types: http://www.ats-lang.org/ http://www.ats-lang.org/
- eternalban 12y agoRe. "logic of truth" vs. "logic of resources". Reminds me of Carl Hewitt. Seen this? http://arxiv.org/abs/0812.4852 http://arxiv.org/abs/0812.4852 (search for { contra godel, direct logic }) Can't find it but he quotes a really interesting exchange between Wittgenstein and Turing (who was attending his class) where W in his inimitable style just waves away paradoxes and says "so what?"
- epenn 12y agoI <3 linear types. Also just thought I'd say hello from over in NSH. :)
- steveklabnik 12y agoWe may end up adding linear types, not just affine, to Rust as well: https://github.com/rust-lang/rfcs/issues/814 https://github.com/rust-lang/rfcs/issues/814
- cwzwarich 12y agoFrom the RFC you linked: "First, the `linear` attribute as described here does not create true `linear` types: when unwinding past a `linear` type, the `linear` attribute will be ignored, and a `Finalize` trait could be invoked. Supporting unwinding means that Rust's linear types would in effect still be affine."
- 12y ago
- fny 12y agoJust a comment: I've noticed Rust literature generally errs on feeling a bit dense and esoteric, which might make things less approachable for some. Then again, that does depend on your target audience. This article doesn't make me feel immediately "fearless" about concurrency, and I'm a fairly experienced programmer and a fan of the language. Perhaps it would have been wiser to start with an approachable example and then taken deep dive about all the nuance from there? Also, are there any plans to integrate tutorial-style guides similar to those from Rust for Rubyists into the Rust book? There's something incredibly fun and real about learning by example. It also would give the reader a chance to read some idiomatic code.
- reklawnos 12y agoWell, Rust by Example already exists: http://rustbyexample.com/ http://rustbyexample.com/ Which has a bunch of examples that utilize most of Rust's features and are runnable/editable in the browser. And there was a comment on /r/rust[1] that made a good point about the documentation: It's better for searching for known-unknowns rather than unknown-unknowns. Since the community is still relatively small and idiomatic Rust is still being defined, it's hard to find those known-unknowns. That being said, I've found that the Rust user forum[2] is very helpful and generally the community is full of people who understand the language way better than I do and who are willing to help. [1]: https://www.reddit.com/r/rust/comments/2zu3eo/what_is_rust_bad_at/cpmobc9 https://www.reddit.com/r/rust/comments/2zu3eo/what_is_rust_b... [2]: http://users.rust-lang.org/ http://users.rust-lang.org/
- deleted 12y ago[deleted]
- steveklabnik 12y ago> Also, are there any plans to integrate tutorial-style guides similar to those from Rust for Rubyists into the Rust book? I'd been waiting for beta to drop to do a re-organization of the TOC of the book. You can see it on nightly here: http://doc.rust-lang.org/nightly/book/ http://doc.rust-lang.org/nightly/book/ I've carved out a whole section, "Effective Rust", specifically for this kind of thing. I'm looking for a better name than "Effective Rust", since that's a very common book title, though. Don't want to be too greedy with that namespace! We do also have Rust by Example, but I admittedly don't give it as much love. Once the book is done...
- Animats 12y agoRust's ownership model, and the borrow checker that enforces it, are a major breakthrough in language design. It's so simple, yet it solves so many problems. This is what Go should have done. Then Go's "share by communicating, not by sharing" would be real, not PR. Go code often passes references over channels, which results in shared memory between two threads with no locking. In Rust, when you do that, you pass ownership of the referenced object. The sender can no longer access it, and there's no possibility of a race condition. A successor to Go with Rust ownership semantics has real potential. Go has a simpler type system than Rust, and seems to be well matched to the back-end parts of web-based systems.
- steveklabnik 12y ago> It's so simple, I think that in hindsight, this may be true, but it took a _very_ long time to figure it out. It took _years_ of iteration before we got to where we are today, and the previous work in this space, which used regions but not borrowing, didn't go further because of the ergonomic issues. In retrospect, hard things often seem obvious, but that's because the work was already done!
- mkehrt 12y agoI'm pretty sure Cyclone used both regions and borrowing in ~2005. But it was a research project and not meant for wide use.
- steveklabnik 12y agoI thought Cyclone only used regions, but I haven't read the paper in a while. (and dates from 2002 IIRC) It certainly had a big influence on Rust, we're fans of the work.
- mkehrt 12y agoIt looks like you're right. I had an undergrad senior thesis in 2006 that futzed around with regions and borrowing, and I know I read some papers on their interactions, but I'm not immediately finding anything chasing references. edit: Of course, I don't mean to diminish the accomplishments of Rust, which had turned these moving parts into a working language. In particular, Rust makes it easy to ignore these issues most of the time.
- eslaught 12y agoI am slightly confused about why the MutexGuard type is required in the locking example. Why can locking a lock not just return &mut? The API as written does so eventually anyway, through access(). I guess the API as written allows you to call access() multiple times, but I do not see how this is a useful property if the mutex stays locked for the entire scope of the MutexGuard anyway.
- aturon 12y agoThe key is that the MutexGuard is responsible for unlocking (and it does so automatically on destruction). That way, you're tying the scope for the &mut reference to the scope in which the lock is actually held.
- Anderkent 12y agoI take it there's no way of tying the lifetime of the MutexGuard to the lifetime of the .access return, so that you don't have to have this intermediate step?
- Jweb_Guru 12y agoThe version presented in the blog post is simplified. In actual Rust, you don't need to write .access, as it is elided using the Deref trait. So in practice there isn't an intermediate step.
- VanillaCafe 12y agoSimilarly, I quite don't understand what in the type signatures precisely tie MutexGuard to the result of access. Like, in the "Disaster averted" example the mutex section, how is it detecting that "error: `guard` does not live long enough"? I see that access returns a borrowed mutable T. But, how does the compiler know that that's borrowed from guard instead of a hypothetical second or third parameter or from some other (global?) state altogether? Edit: Or maybe if a function returns a borrow, then the borrow cannot outlive the scope of the function?
- 12y ago
- carllerche 12y agoRust has definitely been a pleasure to work with. I have been experimenting with a Future & Stream [1] abstraction in Rust that would allow easily describing complex concurrent and async operations and to allow easy composition, not unlike ES 6 promises. The interesting thing is that, thanks to Rust's ownership system, it is easy to discover when handles to a future value go out of scope. This allows the library to reuse internal resources to make the overhead of using the library as light as possible. For example, a Stream is modeled as a sequence of futures (more specifically a future of the next value and a new stream representing the rest of the values, kind of like lazy-seq in clojure but async), but instead of allocating one future for each iteration of the stream, the same internal structure is reused while still being able to expose this API. [1] https://github.com/carllerche/eventual https://github.com/carllerche/eventual
- jbandela1 12y agoJust looked at eventual. It seems really interesting. I looked at Rust's std Future and was turned off by the fact that is blocking.
- Ygg2 12y agoRust is blocking, there was mio crate which brought non-blocking IO operations.
- carllerche 12y agoWell, Rust doesn't have any opinions regarding blocking or not. Currently, std::io implements blocking IO, but as you pointed out, Rust allows libraries to implement non-blocking / async paradigms.
- steveklabnik 12y ago"Rust is so low-level that IO is a library concern, not a language concern," as I like to say.
- jewel 12y agoSorry if I'm missing something obvious, but how do these locks stop a deadlock from happening? To explain, say that I have some code that locks A, then locks B, then does something, and another bit of code that locks B, then locks A, then does its thing. There's a race condition that can happen where one thread has A and the other thread has B. This has bitten me so much that I avoid fine-grained locking when possible and instead use a single global lock everywhere, and have new threads start in the locked position, and then only selectively unlock the bits of code that I can prove are thread-safe, or adding fine-grained locks only where absolutely necessary as shown by benchmarking.
- steveklabnik 12y ago> Sorry if I'm missing something obvious, but how do these locks stop a deadlock from happening? This is the difference between a data race and a race condition. We can't generally prevent deadlocks, I would imagine that's (like all race conditions) is an unsolvable problem at the language level. Maybe some PhD will prove me right or wrong, though...
- Jweb_Guru 12y agoDeadlocks can be statically prevented by ensuring that all code paths acquire locks in the same order. However, Rust's type system is not capable of enforcing that by itself (except maybe in some very limited cases). Some other substructural type systems (e.g. http://en.wikipedia.org/wiki/Substructural_type_system#Ordered_type_system http://en.wikipedia.org/wiki/Substructural_type_system#Order...) might be up to the task, but I'm far from an expert in this area.
- steveklabnik 12y agoAh thank you! This is super neat.
- rntz 12y agoPreventing deadlocks is not an unsolvable problem. Linear-session-typed process calculi are guaranteed deadlock-free and race-free. (The connection with Rust's ownership type-system makes me wonder if there might be some way to backport this guarantee to Rust, but I suspect the connection doesn't go far enough.) This comes at a price, however: certain process topologies are impossible to construct, and there's no way to ask "give me the first message to arrive on either of these two channels" (no Unix `select()` analogue). The latter in particular bugs me, because `select()` is a necessity in practice. In general, problems of "guarantee property X" can almost always be solved with a sufficiently advanced type system, but at the cost of (a) inventing and using a sufficiently advanced type system and (b) disallowing some perfectly good programs.
- jrapdx3 12y agoFWIW I thought the article was quite informative and well-written enough to make the concepts easy to grasp. I'd agree with the opinion that Rust is breaking new ground in an interesting way, and over the next several years I wouldn't be at all surprised to see its ideas becoming quite influential. The discussion points out something else that too often receives too little attention. That is, the quality of documentation is extremely relevant to product success. Sadly, software is more often than not poorly documented, not only frustrating for potential users, but an unnecessary impediment to uptake of the program. It appears the Rust developers are serious about describing how Rust works. That's a very favorable sign of their commitment to the project and speaks volumes about dedication to grow the Rust community.
- divs1210 12y agoCan someone please write a Clojury lisp that compiles to Rust without immutability (by default) and concurrency primitives, since thread safety is guaranteed by the rust compiler? I love Clojure, but this would be a completely different beast, a crazed DRAGON probably. PS: I want a Dragon
- mlitchard 12y agoI can't wait for a mature idris+mature rust. It will be a better world then.
- badsock 12y agoIt makes me sad that Idris is (explicitly) never going to be an industrial language - so many nice things in it.
- deleted 12y ago[deleted]
- ane 12y agoWhy not? Is it in its mission to never become one?
- mlitchard 12y agoI think it will do just fine as an industrial language, when you have the senior architect being the idris expert. His job will be to write the DSL for the engineers to code in. Idris already has hooks into C and Java and who knows what else by then. It won't work well if you expect to replace your java brigade with an idris brigade. Why would you need one anyway? I wonder if I'm being naive.
- mcguire 12y agocough, cough, ATS, cough...
- mlitchard 12y agoThanks for the heads up. I just googled.
- tatterdemalion 12y agoRust's concurrency primitives are as powerful as its semantic concepts are expressive - both stunningly so for a language that compiles to this level. Yesterday I wrote a macro to build simple actors[1], without a care for robustness (this was just a rough draft and I didn't expect it to even work so quickly - amazingly it did!). Now I'm looking at how to fill it out and make it generally useful and get this: I didn't even try to handle failure yet, but it already responsibly joins the thread and deallocates its resources as soon as the actor can no longer receive messages. Automatically! As a natural consequence of Rust's memory model and type system. Despite the fact that Rust knows nothing about concurrency at the language level. [1] https://github.com/withoutboats/Chekhov https://github.com/withoutboats/Chekhov
- halayli 12y agoeverything mentioned can be done in C++11 and lthread_cpp http://lthread-cpp.readthedocs.org http://lthread-cpp.readthedocs.org
- Jweb_Guru 12y agoWhat is interesting is not so much that Rust has shared-memory concurrency (BTW, isn't lthread a M:N threading library? Everything in the article is 1:1) but that it can make this statically safe. Perhaps I am missing something, but I see no evidence from your repository that lthread enforces any of the static safety guarantees discussed in the article, which is not surprising as many of them fundamentally depend on lifetimes and borrowing.
- halayli 12y agoPossible M:N.. by default it's 1:1. It's 1 lthread scheduler per actual pthread. static safety guarantees can come with auto pointers (unique_ptr in particular). This is why I said lthread_cpp & C++11.
- Jweb_Guru 12y agostd::unique_ptr is a significant improvement over prior options, but it can neither ensure correct usage of a mutex (in the sense that it can't cause a data race) nor preserve data race safety for references into another thread's stack. Both of these rely on Rust's ability to limit reference lifetimes, which C++11 doesn't really have (C++14 has an extremely limited form of it in rvalue references, but it's not sufficient to replicate what's in this article). unique_ptr also can't really statically guarantee uniqueness (it's done at runtime instead), meaning it doesn't quite work with channels; and in combination with other C++ features (such as references or shared_ptr) you can also see data races through it, since it doesn't prevent mutation; thus, it isn't able to guarantee safety for use with channels either.
- halayli 12y agounique_ptr transfers ownership. No 2 threads can be working on the same object unless you go out of our way to cheat unique_ptr behavior. Statically or at runtime guarantees don't buy me much. Regarding mutations, const and copy/move constructors give you want u want. Generally, all you need to do is have 1 thread create an std::unique_ptr<Class> object and pass it to the channel for other thread to pick it up.
- deleted 12y ago[deleted]
- westoque 12y agoAnd here's me, happy building apps with Erlang/Elixir with their concurrency model.
- lukego 12y agoImmutability sure makes this stuff easy in Erlang. EriPascal, an ancestor of Erlang, used runtime ownership for passing mutable binaries around. Once you send the binary in a message it is a runtime error to use it again afterwards.
- unfamiliar 12y agoI'd just like to say that I found the tone of this article so much better than all of the other rust guides I have looked at. It managed to be interesting without being annoyingly cute or overly dry or explaining basic concepts which any programmer will know. It makes me want to go back and have another look at the language because it presents the ideas and upsides in such a pleasant manner. Well done.