Mutex but non-blocking on reads?

Hey,
is there a shared memory primitive somewhere in the rust libraries that allows for reads to be immediete? And only block on writes. Maybe this is doable with some protocol based on traditional locks, but I don't see any idea now.

What should happen when there's a writer currently holding the lock and some reader wants to also acquire the lock?

3 Likes

Also, I'm wondering: what's the point of a (write) lock if it can be bypassed?

If having multiple copies of the synchronized data is fine then arc-swap or left-right might do the job.

1 Like

RCU pattern allows zero cost read lock and near-zero cost release, at the expense of making write lock more costly. Linux kernel uses it extensively and proved that it's more efficient than rwlock if the read access occupies more than 90% of overall access pattern. You can utilize crossbeam_epoch crate to implement this pattern, but honestly this crate only provides very low-level primitives and I'm not aware of any convenient wrapper for it.

1 Like

oh yeah left-right by the Noria guy.
arc-swap looks like what I'm after, thanks!

1 Like

yeah I'd like something like RCU, just already implemented nicely in a crate for me :smiley:

Looks like arc-swap and left-right are the choices

1 Like

Readers are never blocked, but as a trade off I don't need writer to first read data before writing in a single atomic block.

Hey, btw my case is very simple - maybe there's fit-in solution? I really should have mentioned it earlier

I have a binary variable. Reading it can't block. But to update it you don't need to read the value first in an atomic block. So I just need read and set, no locks.

It seems at first glance like std::sync::atomic::AtomicBool is even bit more than I need.

AtomicBool seems like exactly what you need. No locking, reading is free.

2 Likes

Note that even on x86 there are surprises.

Other architectures are worse.

Although this may still work if that's something like AtomicBool stop and you just need to ensure work is stopped some time after you signalled it to stop.

2 Likes

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.