Hello! I am pretty new to Rust.
I have code in which closures and a state (Just a struct) must be shared with 'other threads'. Most often it will be the same thread, just in a different context with closures.
I've read online that the RwLock is the type that I need, given that Mutexes result in deadlocks: I only need one writer, but multiple readers.
Strangely enough, I get a deadlock in my situation as well. It seems totally impossible to me: I've checked in the debugger when the RwLock.write() lock is obtained, it happens only twice:
- Once before the run() function is called. The lock leaves the scope early, so it would be free for others.
- The second time when a read lock is already obtained via the run() function. Obtaining the write lock (in the 'Click' lambda) will cause a deadlock even while there are no other write locks!
I can't explain what's going in. I've checked the local Rust toolchain code (Rust internals) via the debugger, and the first caller leaves the write() and write_unlock() functions as it should. The second caller locks up for some reason.
There's a simple example online on how to use RwLocks. That example does work on the playground, but I can't see why that one will and my code won't. The only real difference would be that it uses real threads instead of closures.
Playground of 'lockup' code - Stuff gets interesting starting at line 91. All of the above is sort of slimmed down code for the types that I am using. Line 119 will cause the lockup.
Playground of working sample.
Can anyone tell me what is going on here? I've written multi-threaded code for much longer but Rust is very stubborn on that subject! (Especially with sharing data)
Perhaps I just need to use Crossbeam or something, but I think there should be no problem with this code in vanilla Rust.
Thanks a ton in advance