Threads, races, locks, async, deadlocks and thread safety
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeConcurrency is when multiple tasks make progress at the same time, but not necessarily simultaneously. Parallelism is when tasks are actually running at the same time, often on multiple CPU cores.
A race condition happens when two or more threads access shared data and try to change it at the same time, leading to unpredictable results.
You can prevent race conditions by protecting critical sections with locks, using atomic operations, or designing your code to avoid shared mutable state.
A deadlock occurs when two or more threads are waiting for each other to release resources, causing all of them to be stuck indefinitely.
A mutex is a lock that allows only one thread to access a resource at a time. A semaphore can allow a fixed number of threads to access a resource, making it useful for limiting concurrency.
A critical section is a part of code where shared resources are accessed. You protect it by using synchronization primitives like locks or mutexes to ensure only one thread accesses it at a time.
A thread pool reuses a fixed set of threads to execute tasks, reducing the overhead of creating and destroying threads and improving throughput, especially in high-load scenarios.
Atomic operations guarantee that a variable is updated in a single, indivisible step, preventing race conditions and ensuring thread safety without explicit locks.
Async/await uses cooperative multitasking and an event loop, allowing tasks to yield control while waiting for I/O. Threads use preemptive multitasking and can run in parallel, which is better for CPU-bound tasks.
Memory visibility means that changes made by one thread to shared variables are visible to other threads. Without proper synchronization, threads may see stale values, leading to bugs.
A read-write lock allows multiple threads to read shared data concurrently, but only one thread to write at a time. This improves performance when reads are more frequent than writes.
Immutable objects can't be changed after creation, so they can be safely shared between threads without synchronization, reducing the risk of race conditions.