UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 3.2 Free with a free account
Synchronization Tools
Introduction to Operating Systems · Chapter 3: Concurrency, Synchronization, and Deadlock PreventionSection 3.2 · lesson 19 of 837 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Introduction to Operating Systems.
Lesson complete
Earn the 3 college credits for Introduction to Operating Systems
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Interrupts and Atomic Operations →← Coordinating ThreadsNext lesson: Interrupts and Atomic Operations →
A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →
In this lesson
Mutexes, semaphores, monitors, and condition variables for coordinating threads.
- Explain how a mutex protects a critical section
- Describe semaphore wait and post and compare counting with binary semaphores
- Explain how monitors and condition variables let threads wait safely
- Predict thread behavior from a semaphore's starting value
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,024 words). Read along, or search it.
Opening Question
One Key on a Hook
A coffee shop has one bathroom, and one key hanging on a hook. If the key is on the hook, you take it and go in. If it isn't, you wait. Nobody has to guard the door, because the key itself is the rule. Operating systems use the same trick, and a few variations on it, to keep threads from tripping over each other.
Roadmap
A Printer, Two Ovens, and a Cake
Sam, who runs a small online bakery, has three versions of this problem in one shop program. One label printer that two threads share. Two ovens that four bakers share. And a shop that mustn't open until the cake is ready. The printer needs a lock. The ovens need a semaphore. And waiting until something becomes true needs a condition variable.
Mutex
Locking a Critical Section
Start with the printer. A lock, also called a mutex, short for mutual exclusion, is a flag that is either free or held. A thread that wants the printer first locks the mutex. If it's free, the thread takes it and goes on. If another thread holds it, the operating system puts the new thread to sleep, until the holder unlocks. The code between lock and unlock is the critical section: the part where only one thread may be at a time. Here, both lines of a label print together. And the thread that locked it must be the one that unlocks it. Like the key on the hook: whoever took it puts it back.
Costs of Locks
Keep Critical Sections Short
Locks are simple, but they cost something. A thread that waits does no work. And a lock that's forgotten, and never released, stalls every thread that needs it. So keep critical sections short: lock, change the shared data, unlock. Lesson 3.3 puts a lock around a real counter.
Semaphore
Dijkstra's Protected Counter
Now the ovens. With two ovens, a lock would let only one baker in at a time, and waste the other oven. A semaphore fixes that. The computer scientist Edsger Dijkstra invented it: a protected counter with two actions. Wait, also called P, says: if the counter is above zero, subtract one and carry on. If it's zero, sleep until someone adds one. Post, also called V, says: add one, and wake a sleeper if there is one. The letters come from Dutch words Dijkstra used. And the operating system makes sure each action completes, without another thread slipping in halfway.
Worked Example
Four Bakers, Two Ovens in C
Here's the bakery in C. The semaphore starts at two: one for each free oven. On a Mac, it's a named semaphore, made with sem open. The unnamed kind, made with sem init, isn't supported on macOS: sem init just fails there. Four baker threads each wait for an oven, bake for a fifth of a second, then post the oven back. A small mutex guards the two numbers the program keeps for itself: how many are baking now, and the most at once.
Running It
Never More Than Two Baking
Build it, and run it. Four bakers, two ovens: at most two were ever baking at the same time. The other two slept inside wait, until an oven came back. Run it again, and it's two every time, because the semaphore never lets a third one in.
Binary Versus Counting
A Semaphore Starting at One
Now change the starting value to one, and the label to match. Rebuild, and run. At most one baker at a time. A semaphore that only ever holds zero or one is a binary semaphore, and it works like a lock. A semaphore that starts at any number, like the two ovens, is a counting semaphore. It guards a pool of identical things. And the binary one has one difference from a lock: any thread may post it, not only the one that waited. That makes it handy for telling another thread: go.
Monitor
Data Bundled With Its Functions
Locks and semaphores work, but they're easy to misuse. Forget one unlock, and the program hangs. A monitor is a safer package. It bundles the shared data together with the only functions allowed to touch it. And it makes sure only one thread is inside those functions at a time, as if the room had a lock built into its door. Java's synchronized methods work this way. In C, you build the same thing by hand, from a mutex and some rules.
Condition Variable
Sleeping Until the Cake Is Ready
A monitor also needs a way to say: wait here until something changes. Sleeping while you hold the lock would block everyone. That's the job of a condition variable. In this program, the main thread waits for a baker thread to set ready. Main locks, finds ready still zero, and calls cond wait. That releases the lock and goes to sleep, in one step. So the baker can lock, set ready to one, and signal, which wakes the sleeper.
Common Mistake
Check Again in a While Loop
The sleeper wakes up holding the lock again. And it must check the fact again, because another thread might have changed it in between. That's why the check is a while loop, not an if. A common mistake is the if: a thread can wake when the fact is no longer true. Run it, and the line prints only after the cake is ready, in every run.
Quick Check
Driver Leaves Before the Box
Quick check. Sam's delivery is the main thread here. It must not leave until the packing thread posts that the box is packed. Ivy, who looks after the computers at a school, tries a first version that starts the semaphore at one. Packing takes a tenth of a second. Pause and predict: which line prints first? Driver leaves prints first. A semaphore that starts at one lets the first wait straight through, so the driver didn't wait at all. Start it at zero instead. Now the wait sleeps until the packer posts, so box packed comes first, every time. The tempting answer assumes that wait always waits. It only sleeps when the counter is zero.
Key Takeaways
Mutex, Semaphore, and Condition Variable
To recap. A mutex lets one thread at a time into a critical section, and the thread that locked it unlocks it. A semaphore is a protected counter: counting for a pool, binary for zero or one. A condition variable lets a thread sleep until a fact changes, and wait releases the lock while it sleeps. And after every wake-up, check the fact again, in a while loop.
About Introduction to Operating Systems at UPI Study
Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Linux vs Operating Systems
Why take it here
Why students take Introduction to Operating Systems with UPI Study
Where the credit goes
Universities that work with NCCRS
Introduction to Operating Systems carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Synchronization Tools
What is the difference between a mutex and a semaphore?
How do semaphore wait and post work?
Why should a condition variable wait be inside a while loop?
What is a monitor in concurrent programming?
About the Introduction to Operating Systems course
How many college credits is Introduction to Operating Systems?
How much does Introduction to Operating Systems cost and what is included?
Which universities accept UPI Study credits?
How long does Introduction to Operating Systems take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Introduction to Operating Systems.
83 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →