samedi 29 janvier 2022

std::mutex in C++ versus std::sync::Mutex in rust

I've always found std::mutex is C++ to be manual and error-prone. I need to manually attribute a certain std::mutex to specific variables and I need to remember to always lock the std::mutex before I access those specific variables.

Then I started learning Rust and I see that in Rust, std::sync::Mutex is a wrapper for objects, similar to how std::tuple in C++ is a wrapper for objects. std::sync::Mutex can be locked, and then it returns an object to access the members. As long as that handle object exists, the std::sync::Mutex stays locked, and it gets unlocked in the destructor (or something, not sure how it works in Rust). My first impression is that that's such a better way to tie a mutex to the data it's supposed to protect!

So my thought was: how can I get this feature into C++? I know that C++ is a powerful choice for creating custom features (e.g. boost) so here's the question:

Are there issues with the way Rust does things? (deadlocking concerns etc.)

Is there a reason that Rust can get away with what it does, that C++ cannot match? (preventing deadlock, borrow checker to keep the mutex locked etc.)

Is there an existing implementation of Rust-style std::mutex wrapper for C++?

Is Rust's implementation broken? (because of deadlock or something)

Or, am I doomed? Is C++ so fundamentally broken?

Aucun commentaire:

Enregistrer un commentaire