Is there a "writer first" RwLock/Mutex?

I have a usecase where writes will be very rare compared to reads, but whenever they happen they have to be done as soon as possible,... from what I see this would be somewhat of an "unfair Mutex" or "unfair RwLock" where the writer always "jumps the queue".

Is there such a thing?

It's actually a "fair" RW lock (also called a write-preferring), not an "unfair" one that allows writer starvation you are looking for. Tokio offers such a lock:

The priority policy of Tokio’s read-write lock is fair (or write-preferring), in order to ensure that readers cannot starve writers. Fairness is ensured using a first-in, first-out queue for the tasks awaiting the lock; if a task that wishes to acquire the write lock is at the head of the queue, read locks will not be given out until the write lock has been released. This is in contrast to the Rust standard library’s std::sync::RwLock, where the priority policy is dependent on the operating system’s implementation.

parking_lot's RwLock is also fair and supports blocking calls to read and write.


You might also be interested in arc_swap - Rust which allows writing without locking at all, at the price of needing to write a full copy of the data.


You might also consider various other forms of RCU (Read-Copy-Update) (which arcswap seems to be a variant of) as well as seqlocks. All depending on you exact usage patterns and data types.

There does seem to be a few crates for this, but I haven't tried any of them myself in Rust yet (I have mostly done this sort of things in C++ in the past).

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.