Sync Primitives

RwLock (Reader Writer Lock)

Reference video | Rust Doc

  • 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 | Rust doc Arc

  • 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.