Threads + Synchronization Flashcards
Difference between process & thread
Processes have separate virtual address spaces, threads share the same virtual address space
Which memory segment is not shared across threads
Stack memory - each thread gets its own stack
Data Race Problem
Multiple threads accessing and writing to the same memory at the same time, overwriting each others’ result
Non-deterministic outcome
The output of a non-deterministic program can be different each time it is run
Race Condition
A condition in which the correctness of a program depends on the timing/order of operations
Mutex lock
Mutual Exclusion lock - a primitive that allows only one thread to hold it
Blocking
A thread “waits” until the resource it is trying to access is free. We can’t control the order of threads that are waiting for the lock.
Atomicity
All code that is locked by a lock is atomic, i.e. all sub-operations would run as if they were a single operation, with no interference from other threads
“all or nothing” - runs all operations or none
Serialization
Using a lock serializes operations, only one thread can run operations guarded by a lock
Interleaving
Operations run from different threads are interleaved in some order, we can’t control the order in which different threads run
Thread safe function
A function that doesn’t access shared resources or provides proper protection for critical sections
Re-entrant function
Produces the correct output even when called again while being executed, therefore doesn’t use any shared variables
Deadlock
A set of threads hold a resource and wait to acquire a resource held by a different thread
Conditions for deadlock to occur
- Hold and wait - a thread is holding one resource and waiting for another
- Circular waiting - a set of threads is waiting for a resource held by the next thread
- Mutual exclusion
- No preemption - resource only released voluntarily by thread holding it
Livelock
A set of threads are still actively executing instructions but don’t make any progress