Serializing a struct containing a mutex

Interestingly, it's possible to serialize a struct containing a mutex. Is that even meaningful? Would deserializing lock the mutex temporarily, or what?

Playground doesn't have "json" as a supported crate, so I can't try this fully in Playground. Derive works, though.

Why wouldn't it be meaningful?

You mean serde_json.

It actually works. Serialization locks the data temporarily.

Serialization locks the datum (as it must do, since there is no other way to read the value without obtaining a lock or consuming the RwLock), yes. However, the resulting serialized data is then independent of the lock and of the original record.

If you deserialize it, you end up with a new Item with a new lock, containing an equivalent value. The two can be treated exactly as if they are two totally separate locks, since that's what they are: Rust Playground

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.