Critical section and mutex
The critical section and mutual exclusion, what a correct solution must guarantee, the atomic operation, the POSIX mutex (lock, unlock, trylock), busy waiting versus blocking and lock granularity.
- 27 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Critical section: what is it?
Show the answer
The part of the code that reads or modifies shared data and that only one thread at a time may run.
It is defined by the data it touches, not by the function: printing a message is not part of it, updating a shared balance is.
Two threads each run this function, with no lock, and
soldestarts at 100. Which final values are possible?
```c
int solde = 100;
void *depot(void *arg) {
int tmp = solde;
tmp = tmp + 50;
solde = tmp;
return NULL;
}`150or200- Always
200 - Always
150 100,150or200
Show the answer
150or200If both threads read 100 before either writes, each writes 150 and one deposit is lost. If one finishes before the other reads, the result is 200. The value 100 is impossible: each thread writes at least 150.
A correct solution to the critical-section problem guarantees …, … (a thread outside the section does not block the others) and … (no thread waits forever).
Show the answer
A correct solution to the critical-section problem guarantees mutual exclusion, progress (a thread outside the section does not block the others) and bounded waiting (no thread waits forever).
All three are needed: a lock never released respects exclusion but breaks progress, and a thread always overtaken breaks bounded waiting.
Mutual exclusion: what is it?
Show the answer
The guarantee that at any instant at most one thread is inside a given protected zone of code.
It is what rules out faulty interleavings: while one thread is in the zone, the others wait at the door.
A transfer locks the mutex, checks the balance, calls
sleep(2)to simulate a bank validation, updates the balance, then unlocks. With ten simultaneous transfers, the program takes twenty seconds. What should be fixed?- Replace the mutex with busy waiting
- Remove the mutex, since the sleep already slows the threads down
- Create a different mutex for each transfer
- Move the validation out of the lock, which then covers only the balance
Show the answer
Move the validation out of the lock, which then covers only the balance
During the sleep, the lock is held for nothing: the other nine transfers wait. The lock must cover the critical section and nothing else. A mutex per transfer would exclude nothing: each would take its own without bothering the others.