💾 Archived View for carnage.edvinbasil.com › knowledge › pl › rust › sync-primitives.md captured on 2021-12-17 at 13:26:06. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2020-11-07)

-=-=-=-=-=-=-

Sync Primitives

RwLock (Reader Writer Lock)

[Reference video](https://youtu.be/8O0Nt9qY_vo?t=6537) | [Rust Doc](https://doc.rust-lang.org/std/sync/struct.RwLock.html)

- An `RwLock` is basically a `RefCell` whose counters are kept using atomics

- the `read` (borrow equivalent for RefCell) and `write` (borrow_mut equivalent of Refcell)

always return the ref/refmut instead of an option so that we dont have to

manually poll in a loop. They block the current thread till its available if

the borrow cannot succeed yet

Mutex

- A `Mutex` can be considered as a simplified version of `RwLock` where ther is

only borrow_mut. So a `Mutex` doesnt have to keep a state to count the no. of

readers becuse its either we have the reference or someone else has it. `Mutex`

also blocks the thread till it gets a value

Arc (Atomic reference counted)

[ Reference Video timestamp ](https://youtu.be/8O0Nt9qY_vo?t=6664) | [Rust doc Arc](https://doc.rust-lang.org/std/sync/struct.Arc.html)

- Thread safe reference counting pointer

- Almost similar to `Rc` except that it uses thread safe atomic operations to

manage the reference count

Condvar

- Provides a way to wait/block a thread and wake it up without using up cpu

cycles

- When paired with a mutex, we can use it to wake up the thread waiting for the

mutex at the _same time_ as when we release the lock. This requires that we

currently holds the lock on the mutex.