Name: Alex Rivera
Course: CS 350 - Operating Systems
Date: October 14
Question 1: Define a race condition and provide a brief example of how it occurs in a multi-threaded application.
A race condition occurs when two or more threads access shared data and try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, the final state of the data depends on the sequence or timing of the threads' execution. [TODO: REWORD THIS IT SOUNDS TOO MUCH LIKE WIKIPEDIA] For example, if Thread A and Thread B both try to increment a shared counter variable at the exact same time without a lock, they might both read the value as '5', increment it locally to '6', and write '6' back. The counter should be 7, but due to the race condition, an increment is lost.
Question 2: What are the four necessary conditions for a deadlock to occur (Coffman conditions)?
1. Mutual Exclusion: At least one resource must be held in a non-sharable mode.
2. Hold and Wait: A process is holding at least one resource and requesting additional resources held by other processes.
3. No Preemption: Resources cannot be forcibly taken from a process; they must be released voluntarily.
4. Circular Wait: [Wait what was the exact definition for this one? Look at lecture slides from Tuesday] Basically P1 is waiting for P2, P2 is waiting for P3, and P3 is waiting for P1.
Question 3: Write a simple pseudocode example using a Mutex lock to protect a critical section.
I'm going to use standard POSIX thread style logic for this:
pthread_mutex_t my_lock = PTHREAD_MUTEX_INITIALIZER;
int shared_balance = 1000;
void* withdraw(int amount) {
pthread_mutex_lock(&my_lock); // Enter critical section
if (shared_balance >= amount) {
shared_balance -= amount;
}
pthread_mutex_unlock(&my_lock); // Exit critical section
}
-- Make sure to run this in gcc to see if I forgot any semicolons before submitting --