Synchronization Tools, Explained

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

← 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 →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

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.

Compare: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A mutex lets one thread at a time into a critical section, and the thread that locked it must unlock it. A semaphore is a protected counter that can admit several threads at once, such as two bakers for two ovens. A binary semaphore holding only 0 or 1 works much like a lock, except any thread may post it, which makes it useful for signaling.
How do semaphore wait and post work?
Wait, also called P, subtracts one from the counter if it is above zero and carries on, but sleeps if the counter is zero. Post, also called V, adds one and wakes a sleeping thread if there is one. Edsger Dijkstra invented the semaphore, and the letters come from Dutch words. The operating system makes each action complete without another thread slipping in halfway.
Why should a condition variable wait be inside a while loop?
A condition variable wait belongs inside a while loop because a thread can wake up when the fact it waited for is no longer true. Another thread may change the data before the sleeper runs again, so it must check the fact once more after waking, now holding the lock. Using an if instead of a while is a common mistake.
What is a monitor in concurrent programming?
A monitor is a safer synchronization package that bundles shared data with the only functions allowed to touch it, and lets only one thread inside those functions at a time. Condition variables let a thread inside wait for something to change without blocking everyone. Java's synchronized methods work this way, while in C the same pattern is built by hand from a mutex and some rules.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Introduction to Operating Systems
3 credits · NCCRS
Enroll →