What is Synchronization
-
Coordination b/w processes/threads to access shared resources so that deadlock & race conditions can be avoided.
Ex-1? When multiple threads need to modify a shared resource(eg: global variable) we should lock the resource to guarantee at most 1 thread can do modification.
Ex-2? When 2 threads are putting data on top of stack, without synchronization it's immpossible to tell what is on top of the stack at any one time.
Rust Synchronization Methods
Name | Description | Advantage, Disadvantage |
---|---|---|
Arc(Atomically Reference Counted) Shared Read-Only Access |
IPC: No Synchronization: Yes |
Disadv: Immutable Reference to data. Data cannot be modified. |
Channels (std::sync::mpsc) |
IPC: Yes (Safe message passing) Synchronization: Yes (block until both sender and receiver are ready, providing built-in synchronization) |
|
Mutexes and RwLocks | Synchronization: Yes |
Disadv: Plain mutex cannot be used across threads. |
Arc <Mutexes> | Synchronization: Yes |
Adv: Mutex inside Arc can be used across threads |
Atomic Types (std::sync::atomic) | Provides low-level atomic operations | |
Pipes |
IPC: Yes Synchronization: No |
|
Shared Memory | Yes(allows multiple processes to access the same memory space) | |
Condition Variables(std::sync::Condvar) | work with mutexes to allow threads to wait for specific conditions | |
Barriers and Semaphores | Yes |
Questions on Synchronization
-
Dining Philospher