by ajross · 4y ago · 0 comments
But the flip side is that naive Rust code just isn't useful for multithreaded work and tends to require heavier abstractions (e.g. copy "commands" or whatever in and out of queues vs. just taking a lock around some shared data). I occasionally try to look at the natural way one expresses the kind of stuff we do in Zephyr in a Rust kernel, and... there's really not much there besides copious and extensive use of unsafe.
You can take a lock around some shared data; the standard library has such a thing. If the standard library lacked such a thing, then you could implement that abstraction in unsafe, but that at least narrows the amount of code you need to reason about the thread-safety for. Of course that only prevents data-races, not deadlocks and livelocks.
Most code that you can't "just do" in Rust is code that really should have a lot of eyeballs on it were it implemented in some other language. Kernel code gets a lot of eyeballs, usually a lot of testing, and still ends up with fielded bugs[1].
For kernel code, I imagine Rust shines for device drivers; TFA applies well there; a multithreaded kernel could have thread-oblivious device drivers and no future "optimization" would accidentally share data between threads.
There are data-structures and algorithms that put you in conflict with Rust's type system (a non-concurrency one that comes to mind is trees with parent pointers). Sometimes the solution is to pick a different data-structure, other times it is judicious use of unsafe.
1: Note that the same is true with parts of the Rust stdlib that are implemented with unsafe.
struct Shared { /* ... */ }
#[derive(Clone)
struct Context {
shared:Arc<Mutex<Shared>>
}
impl Context {
fn do_stuff (&self) {
let shared = self.shared.lock();
/* ... */
}
fn do_more_stuff (&self) {
let shared = self.shared.lock();
}
}
What's wrong with that? You have a bunch of safety guarantees here :- mutex poisonings are detected (you can use try_lock to recover from them)
- the shared data isn't leaked and guaranteed to live long enough in each calling context
- the Mutex implementation doesn't suck and iirc supports reentrant code without deadlocks, making it safe to use on the same thread
- it's really easy to call `context.clone()` to send it wherever you want
I don’t think that’s true, at least in the “rust mutexes are reentrant” sense: a mutex hands out &mut refs, a reentrant mutex would mean concurrent &mut, which is illegal.
However rust does allow handing out the one &mut to callees, without fear that it will be leaked and outlive the lock or anything, so this sort of “reentrancy” is fine if you split functions into lock acquisition and actual processing.
IME deadlocks (and self-deadlocks) remain the biggest issue in concurrent rust. Lock ordering concerns are especially frustrating when fine-locking.
#[derive(Clone)]
struct S {
a: Arc<Mutex<A>>
}
impl S {
fn reentrant(&self) {
let cloned = self.cloned();
let locked = self.a.lock();
if condition {
cloned.reentrant();
} else {
/* do stuff */
}
}
I believe it will not deadlock. Reentrant mutexes are pretty common implementations - is that not true in Rust right now?https://play.rust-lang.org/?version=stable&mode=debug&editio...
The parent comment correctly explained that it would be incorrect for a Mutex<A> to hand out unique references &mut A to multiple call frames simultaneously. If it did, one of them could be passed to another thread and accessed concurrently with the other one to create race conditions.
https://doc.rust-lang.org/std/sync/struct.Mutex.html#method....
“The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).”
The parking_lot crate has a ReentrantMutex<A> that would not deadlock here. It hands out shared references &A instead of unique references &mut A. If you want to be able to mutate the value, you can wrap it in a type with interior mutability (Cell or RefCell), and then the type system will prevent you from passing those references to other threads.
https://docs.rs/parking_lot/latest/parking_lot/type.Reentran...
Slightly inaccurate. You can recover from them with `lock` too. In fact, to _not_ attempt to recover from them, your code should have looked like:
let shared = self.shared.lock().expect("mutex poisoned!")
as `lock` returns a `Result`.The difference between `try_lock` and `lock` is unrelated: `try_lock` fails fast if it's not possible to take the mutex immediately.
Can’t you do this in Rust with std::sync::Mutex and similar?
This is the synchronized value pattern [1]. I'm pretty sure that my 3rd edition of "The C++ programming Language" by Bjarne had a description of it and it predates rust by at least a decade.
[1] https://www.boost.org/doc/libs/1_80_0/doc/html/thread/sds.ht...
for (auto foo : bar.wlock()) {
baz(foo);
}
You need to do bar.withWLock([](auto &lockedBar) {
for (auto foo : lockedBar) {
baz(foo);
}
});
In rust, the lifetime checking prevents that.The other big gotcha is accidentally blocking while holding a lock. E g. Instead of
auto g = bar.wlock();
baz(*g);
co_await quux();
You should do {
auto g = bar.wlock();
baz(*g);
}
co_await quux();
Or use withWLock. If you co_await with the lock held you can deadlock if the executor switches to a different coroutine that tries to acquire the same lock. If you actually need to hold the lock across the blocking call, you need coroutine-aware locks, which turns it into auto g = co_await bar.wlock();
baz(*g);
co_await quux();
No idea if rust prevents this problem - I suspect not, but I haven't used async rust.There's UnsafeCell type that is a deliberate loophole in immutability of types behind shared references. It's used as the basis for atomic access and mutexes.