race condition Flashcards
(20 cards)
What is a race condition?
A situation where two or more threads/processes access shared data concurrently and the outcome depends on the order of execution.
What causes a race condition?
Concurrent access to shared memory without proper synchronization.
Why are race conditions problematic?
They can lead to unpredictable behavior and bugs that are hard to reproduce.
What is a common symptom of a race condition?
Inconsistent or incorrect program output.
Do race conditions occur in single-threaded programs?
No, they typically occur in multi-threaded or multi-process programs.
What is shared memory?
A memory segment that can be accessed by multiple threads or processes.
What synchronization methods can prevent race conditions?
Mutexes, semaphores, locks, atomic operations.
What programming constructs are used to manage race conditions?
Critical sections, mutual exclusion mechanisms.
Can read operations cause race conditions?
Yes, if a read is made before a write completes, it may read stale data.
Are race conditions deterministic?
No, they are non-deterministic and depend on thread scheduling.
What is a critical section?
A part of the program where shared memory is accessed and which must not be concurrently executed by more than one thread.
How does a mutex help prevent race conditions?
It ensures that only one thread can enter the critical section at a time.
What is the difference between a race condition and a deadlock?
A race condition is about incorrect data due to timing; a deadlock is when threads wait indefinitely for each other.
What is atomicity and how does it relate to race conditions?
Atomicity ensures operations are completed without interruption, preventing partial updates that cause race conditions.
Can compilers introduce race conditions during optimization?
Yes, compiler optimizations can reorder instructions in ways that cause race conditions if memory barriers aren’t used.
Explain how the ‘volatile’ keyword affects race conditions in C/C++.
It tells the compiler not to optimize reads/writes to the variable, but it does NOT prevent race conditions; synchronization is still needed.
Describe a real-world example of a race condition in an OS context.
Multiple threads writing to a log file without a lock could interleave output and corrupt the log.
How can race conditions be detected during development?
Using tools like ThreadSanitizer, Helgrind, or static code analysis.
Why are race conditions difficult to debug?
Because they are timing-dependent and may not occur consistently.
How do memory barriers help in preventing race conditions?
They prevent the CPU/compiler from reordering memory operations, ensuring proper sequence of actions.