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.
Different Synchronization Methods
| Name | Description | Synchronization | IPC |
|---|---|---|---|
|
Rust Arc(Atomically Reference Counted) Shared Read-Only Access |
Immutable Reference to data. Data cannot be modified | Yes | No |
| Channels (std::sync::mpsc) | block until both sender and receiver are ready, providing built-in synchronization | Yes | Yes |
| Mutexes and RwLocks | Plain mutex cannot be used across threads. | Yes | |
| Arc <Mutexes> | Mutex inside Arc can be used across threads | Yes | |
| Atomic Types (std::sync::atomic) | Provides low-level atomic operations | ||
| Pipes | No | Yes | |
| Shared Memory | allows multiple processes to access the same memory space | Yes | No |
|
Condition Variables: C++ |
work with mutexes to allow threads to wait for specific conditions | ||
| Barriers and Semaphores | Yes |