Re:Fun facts about Rust's growing popularity
by GlitchMr on Monday October 30, 2017 @12:38PM
(#15586443)
The issue really is lack of scoped threads forcing usage of reference counting to figure out when to drop a value. With crossbeam scoped threads implementation this looks much nicer.
extern crate crossbeam;
use std::sync::Mutex;
fn main() {
let counter = Mutex::new(0);
crossbeam::scope(|scope| for _ in 0..10 {
scope.spawn(|| *counter.lock().unwrap() += 1);
});
println!("{:?}", counter);
}
Four lines to declare a mutex, start 10 threads that all lock that mutex, increase value behind mutex, unlock mutex, and join all spawned threads. There is a lot going on here (unwrap is arguably a noise here however, but the rest is straight to the point).Also, it's possible to use atomic ints here instead of mutex. Verbosity of mutex actually helps a bit, because locking is fairly expensive and it's better to avoid locking if possible.
Re:Fun facts about Rust's growing popularity
by pjmlp on Monday October 30, 2017 @08:46AM
(#15584570)
You can simulate something like that using lambdas in C#.
Something like
withLock(counter, (num) => {
return num + 1;
});
or in alternative, withLock(counter, (ref num) => {
num++;
});
If C# allowed for trailing lambdas it could look better.
But just as a counter-argument, look how a simple lock looks like in Rust [1]:
[1] https://doc.rust-lang.org/book/second-edition/ch16-03-shared...----- edit: Just to clarify my point. The ownership model is a beautiful solution to the resource management problem. And as the parent pointed out, some concepts can be cleanly borrowed/reused in other languages.
But now, in Rust, in practice, you realize that this model requires a lot of boilerplate code just to make the borrow checker happy, even for simple things like using a lock: create Arc(Mutex(data)); clone the arc reference; move the new Arc reference to the new thread.