Concurrency Flashcards
What is concurrency in computer systems?
Concurrency means running multiple tasks at once to make better use of resources and speed things up
How does concurrency differ from parallelism?
Concurrency is managing multiple tasks at once (either by switching between them or running together), while parallelism is actually doing them at the same time using multiple cores
What is a critical section?
A part of code that uses shared stuff, where only one thread should run it at a time to stop mistakes
Define race condition.
When many threads change the same data at once, it can mess things up and give wrong result
What are the three conditions that must be met for a race condition to occur?
Shared resource: Multiple threads are working with the same data.
At least one write: One thread is changing the data.
No synchronization: Threads don’t work together well, so they end up clashing and causing problems
What is mutual exclusion?
One thread or process can access the critical section at a time
What is a mutex?
A tool that lets only one thread access a resource at a time, preventing conflicts
What are the main problems of concurrent systems?
- Race conditions
- Deadlocks
- Starvation
- Livelocks
Define deadlock.
Deadlock happens when threads wait on each other forever, and nothing moves forward
What are the four necessary conditions for deadlock?
- Mutual Exclusion
- Hold and Wait
- No Preemption
- Circular Wait
What is a semaphore?
Controls how many threads can access a resource. It uses a counter to keep track
What’s the difference between binary and counting semaphores?
Binary Semaphore:
➤ Only 0 or 1
➤ Like a light switch (on/off)
➤ Used for mutual exclusion
Counting Semaphore:
➤ 0 or more
➤ Like tickets to a show – limited number
➤ Used for limiting access to a resource
What is starvation?
A thread waits forever as others keep getting the resource
What is a livelock?
Processes keep responding to each other but never finish
What is the difference between preemptive and non-preemptive scheduling?
Preemptive: The OS can stop a running program and switch to another.
Non-preemptive: A program keeps running until it finishes or waits.
What is Peterson’s Algorithm used for?
A software way for two programs to safely share a resource by taking turns
What are the three approaches to avoid race conditions?
Atomic operations: Do something in one go, no interruptions.
Locks or semaphores: Use a key to control access.
Concurrent data structures: Use special tools designed for safe sharing.
How does the lock mechanism work in thread synchronization?
Lets one thread in, and keeps others out until it’s done
What is context switching?
Saving the CPU’s work so it can pick up right where it left off later
What are the performance trade-offs of concurrency?
Pros:
Better CPU use
Faster response time
Cons:
More complex syncing
Harder to debug
Risk of deadlocks