6 ms·
The recommended solution uses "scoped_threadpool". But "scoped_threadpool" uses "unsafe".[1] They could not actually do this in Rust. They had to cheat. The la
by Animats 5y ago
The recommended solution uses "scoped_threadpool".
But "scoped_threadpool" uses "unsafe".[1] They could not actually do this in Rust. They had to cheat. The language has difficulty expressing that items in an array can be accessed in parallel. You can't write that loop in Rust itself without getting the error "error[E0499]: cannot borrow `v` as mutable more than once at a time".
And, sure enough, the "unsafe" code once had a hole in it.[2] It's supposedly fixed.
If you look at the example with "excessive boilerplate" closely, you can see that it doesn't achieve concurrency at all. It locks the entire array to work on one element of the array, so all but one of the threads are blocked at any time. To illustrate that, I put in a "sleep" and some print statements.[3]
You could put a lock on each array element. That would be a legitimate solution that did not require unsafe code.
To do this right you need automatic aliasing analysis, which is hard but not impossible. (Been there, done that.) Or a special case for "for foo in bar", which needs to be sure that all elements of "bar" are disjoint".
[1] https://github.com/reem/rust-scoped-pool/blob/master/src/lib.rs https://github.com/reem/rust-scoped-pool/blob/master/src/lib...
[2] https://www.reddit.com/r/rust/comments/3hyv3i/safe_stable_and_scoped_threadpool https://www.reddit.com/r/rust/comments/3hyv3i/safe_stable_an...
[3] https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e6ce779782d5234091cf8d39a4532389 https://play.rust-lang.org/?version=stable&mode=debug&editio...
- jzoch 5y ago> They could not actually do this in Rust. They had to cheat. That isn't true at all. The implementation of scoped_threadpool being in rust is all the evidence you need that they did not cheat. unsafe is a perfectly valid construct in rust that does not subvert its benefits. It just is a reversal of the defaults in other languages (unsafe by default - opt-in to safer constructs like smart_ptr). People freak out too much over this stuff. If you are learning - feel free to use escape hatches from "idiomatic rust" but recognize that you aren't being idiomatic (and therefore may be handicapping your learning!). Its okay to use unsafe despite idiomatic rust trying to avoid it unless necessary (and even then providing safe wrappers over it). Its also okay to use Arc<Mutex> and the like if you need to just recognize there may be a better way.
- steveklabnik 5y agounsafe is not cheating. It is part of the language for a reason, there to be used when appropriate. It is literally impossible to make a useful program without any unsafe code anywhere, because there aren’t Rust CPUs. By this definition, “Rust” does not exist. thread::spawn uses unsafe code. sleep uses unsafe code. Is your own example not in Rust? Are you cheating? (And yes, the spawn version isn’t optimally concurrent. The comment was long enough without getting into that. People struggle to get examples to compile before they worry about things like this. That would be next steps.)
- Animats 5y agoIf you need "unsafe" in pure Rust code, not to talk to something external, the language has failed you at some point. There are a relatively small number of trouble spots. They include, at least: - No way to talk about partially initialized arrays in Rust, which leads to Vec needing "unsafe". - Back references, which makes some kinds of trees, and of course doubly-linked lists, difficult. Those I've mentioned before. From the discussion above, add: - Problems around interior mutability within arrays, where you need some way to say, and prove, "a is disjoint from b", before working separately on a and b. These are classic proof of correctness areas. It's fairly straightforward to state the conditions that have to be proven, and usually not that hard to prove them. The RustBelt crowd seems to be working on this. Maybe they'll come up with a way to prove out conditions like that, short of grinding away by hand in Coq. Most of those problems are within reach of a fully automatic prover, like a SAT solver.
- zozbot234 5y ago> These are classic proof of correctness areas. It's fairly straightforward to state the conditions that have to be proven, and usually not that hard to prove them. You're right, but current Rust cannot express logical preconditions in code, much less compiler-checkable proofs. Many groups are working on this via a variety of approaches, but it will take some time before there's a common standard for expressing these things as part of the Rust language itself.
- pjmlp 5y ago
- herbstein 5y ago> But "scoped_threadpool" uses "unsafe".[1] They could not actually do this in Rust. They had to cheat. Using unsafe isn't "cheating". The whole point of using Rust is that you can encapsulate very small amounts of "unsafe" code within a safe abstraction, and know that there is no way to abuse the safe APIs to produce undefined behavior. The formal verification project "RustBelt" [0] has proven exactly this -- safe Rust code composes arbitrarily to produce safe behavior. There is still a burden of proof on anyone writing a safe function that uses unsafe functionality internally. Keep in mind that "unsafe" Rust still poses more restrictions on the programmer compared to raw C/C++. > The language has difficulty expressing that items in an array can be accessed in parallel. The Rust borrow semantics is based on `exclusive XOR shared` references. At the first order of approximation it's not possible to mutate a value through a shared reference. Interior mutability complicates this image somewhat, but it's enough to explain why what you wrote is wrong. Spawning `n` threads and giving each thread a mutable reference to the vector `v` goes against the above borrow semantics because that would result in `n` exclusive references. Only through exclusive references is mutation allowed. Since this is not allowed it becomes a compile-time error. In other words, it's not that the language has "difficulty expressing" that scenario. It was explicitly designed to not allow it. [0]: http://plv.mpi-sws.org/rustbelt/
- Animats 5y agoUsing unsafe isn't "cheating". The whole point of using Rust is that you can encapsulate very small amounts of "unsafe" code within a safe abstraction, and know that there is no way to abuse the safe APIs to produce undefined behavior. The formal verification project "RustBelt" [0] has proven exactly this -- safe Rust code composes arbitrarily to produce safe behavior. "Within a safe abstraction" is the question. The question is whether a piece of encapsulated code is always memory-safe for all uses. There's no guarantee of that from the language. The RustBelt people are working on tools for that, but it will probably require proof work in Coq for each bit of code containing "unsafe" to get there. Look at the scoped_threadpools example again [2] use scoped_threadpool::Pool; fn main() { let mut pool = Pool::new(3); let mut v = vec![1, 2, 3]; pool.scoped(|scope| { for i in &mut v { scope.execute(move ||{ *i += 1; }); } }); println!("v: {:?}", v); } There's an implicit assumption here that all the values returned from the iterator at for i in &mut v are disjoint. But iterators, in general, do not guarantee disjoint outputs. An iterator which returned each reference value twice, for example, is a valid iterator. But used in the context above, two threads would receive mutable access to the same element of a vector. That seems to violate a core Rust safety assumption. This would be a nice test to run through the version of the Miri interpreter that implements the dynamic "stacked borrow" checks from the RustBelt group.[2] That tool should catch this. [1] https://news.ycombinator.com/item?id=24992747 https://news.ycombinator.com/item?id=24992747 [2] https://plv.mpi-sws.org/rustbelt/stacked-borrows/paper.pdf https://plv.mpi-sws.org/rustbelt/stacked-borrows/paper.pdf