Rust is my favorite programming language. I've been writing Rust for about 6 years, from college to professionally, and I'm vocal about how helpful th

Rust's Sneaky Deadlock With `if let` Blocks | Brooks Blog

submited by
Style Pass
2024-11-06 16:30:05

Rust is my favorite programming language. I've been writing Rust for about 6 years, from college to professionally, and I'm vocal about how helpful the compiler is in catching particularly nasty multithreaded issues and memory bugs. What the compiler doesn't always catch though is deadlocks, which can occur using several well known types like Mutex and RwLock.

Generally, this is fine, and you can sus out if a program is going to cause a deadlock by just making sure you aren't acquiring multiple simultaneous locks. This post is going to focus specifically on the former situation, which is acquiring multiple simultaneous competing read/write locks on the same resource. Take this snippet for example:

This program will deadlock during the statement that attempts to acquire a write lock on the map. Preventing this can take many forms, the simplest being to drop the read lock before acquiring the write lock:

So in a single-threaded case with competing locks, there are fairly simple ways to prevent this from happening. Now for the trouble.

Leave a Comment