Mutual Exclusion, Explained

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 3.4 Free with a free account

Mutual Exclusion

Introduction to Operating Systems · Chapter 3: Concurrency, Synchronization, and Deadlock PreventionSection 3.4 · lesson 21 of 836 min · free with a free account

← Interrupts and Atomic OperationsNext lesson: Deadlocks →

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

The three requirements for a correct lock and Peterson's two-thread solution.

  • Identify the entry, critical, exit, and remainder sections of a thread's loop
  • Explain the mutual exclusion, progress, and bounded waiting requirements
  • Show why strict alternation and a flags-only rule fail
  • Explain how Peterson's solution meets all three requirements for two threads

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 (878 words). Read along, or search it.

Opening Question

One Sign-Out Sheet at the Help Desk

Ivy, who looks after the computers at a school, keeps one sign-out sheet at the help desk for the loan laptops. Only one person may write on it at a time. That sounds easy, until you ask two more questions. What if the sheet sits free, and people still stand there waiting? And what if one busy student keeps cutting in front of everyone else? A good rule for one at a time has to handle those cases too. This lesson shows what a correct rule needs, and a famous way to get one.

Definitions

Entry, Critical, Exit, and Remainder

A critical section is the stretch of code where a thread uses shared data, data that other threads also change, like the load, add and store of a counter. Mutual exclusion means that while one thread is inside its critical section, no other thread is inside theirs. Each thread's loop has four parts. The entry section asks to go in. Then comes the critical section. The exit section says: I'm done. And the remainder section is everything else. The rules for taking turns live in the two parts around the critical section: the entry, and the exit.

Three Requirements

Exclusion, Progress, and Bounded Waiting

It's easy to write an entry rule that keeps threads apart. The hard part is doing it well. A correct solution must meet three requirements. Mutual exclusion: never two threads in the critical section at once. Without it, updates get lost. Progress: if nobody is inside and someone wants in, one of the threads that wants in gets in soon. A thread that isn't interested must not hold up the others. Bounded waiting: once a thread asks, only a limited number of others may go in ahead of it. Without it, one thread can be passed over again and again. That's called starvation. A common mistake is to think mutual exclusion alone makes a good lock. A lock nobody can ever get also keeps everyone apart!

Failed Attempt

Strict Alternation Breaks Progress

Here's a tempting rule that fails. Two threads share one variable, turn. A thread may enter only when turn holds its own number. On the way out, it hands the turn to the other thread. This strict alternation does guarantee mutual exclusion. But in this program, thread zero wants in three times, and thread one wants in only once. Each wait gives up after a hundred million checks, so the program can report instead of hanging forever. Build it, and run it. Thread zero got in twice, not three times. Its third turn could only come from thread one, and thread one had finished and left. The critical section sat empty, and thread zero waited for nothing. Strict alternation breaks progress.

Peterson's Solution

Flags Plus an After-You Turn

In 1981, the computer scientist Gary Peterson published a neat solution for two threads, using only shared variables. Each thread has a flag that says: I want in. And a shared turn variable breaks ties. The key move is generous. Before entering, a thread sets turn to the other thread, as if to say: after you. Then it waits only while the other one wants in, and it's the other one's turn. If both want in at once, the one that wrote turn last gives way, and the other goes first.

Checking the Rules

Meeting All Three Requirements

Now check it against the three requirements. Mutual exclusion: turn holds one value, so it can't favor both threads at once. Progress: if the other thread isn't interested, its flag is down, and the wait ends at once. Bounded waiting: a thread that leaves must write turn again before it can come back in, and that hands the waiting thread its chance. So a waiter is passed over at most once. Build it, and run it: two threads, fifty thousand additions each, and the total is exact.

Warning

Atomic Variables and Memory Order

One warning. The flags and turn here are atomic ints, and that matters. On a modern CPU and compiler, ordinary variables can be reordered, or kept in registers, so the two writes may not be seen in the order the code gives. Atomic types use the strongest ordering by default, which adds the memory barriers Peterson's reasoning needs. And Peterson's solution works for exactly two threads. Real programs use the library's mutex, which the OS and special CPU instructions make correct for any number of threads.

Quick Check

Two Raised Flags, Nobody Enters

Quick check. Here's a simpler entry rule, with no turn variable: raise your flag, then wait while the other thread's flag is up. To force the unlucky timing, both threads raise their flags before either one checks. Pause and predict: what happens? Neither one gets in. Each thread sees the other's flag up, and waits for it to drop. But each flag drops only after its owner gets in. Run it: both report zero. Without the give-up limit, they'd wait forever. Nobody is inside, both want in, and nobody gets in. That breaks progress. Mutual exclusion holds, which is why this rule looks safe at first. It's a small deadlock, and deadlock gets its own lesson, 3.5.

Key Takeaways

What a Correct Entry Rule Needs

To recap. A thread's loop has an entry, a critical section, an exit, and a remainder. The rules live in the entry and the exit. A correct rule needs mutual exclusion, progress, and bounded waiting. Strict alternation keeps threads apart, but breaks progress. And Peterson's solution meets all three for two threads, as long as its variables are atomic.

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 Mutual Exclusion

What are the three requirements for a solution to the critical section problem?
A correct solution must provide mutual exclusion, progress, and bounded waiting. Mutual exclusion means no two threads are ever in the critical section at once. Progress means that if nobody is inside and some thread wants in, one of the threads that wants in gets in soon. Bounded waiting limits how many others can enter ahead of a thread that has already asked.
Why does strict alternation fail as a mutual exclusion solution?
Strict alternation keeps threads apart but breaks the progress requirement. Two threads share a turn variable, and each may enter only on its own turn, handing the turn over on exit. If one thread wants in three times and the other only once, the first thread gets stuck after its second entry, waiting for a turn its finished partner will never hand back.
How does Peterson's solution work?
Peterson's solution, published by Gary Peterson in 1981, gives each of two threads a flag meaning I want in, plus a shared turn variable. Before entering, a thread raises its flag and sets turn to the other thread, as if saying after you. It waits only while the other thread wants in and has the turn. On modern hardware, the variables must be atomic.
Why is raising a flag and waiting not enough to protect a critical section?
A rule where each thread raises its flag and waits while the other flag is up can leave both threads stuck. If both raise their flags before either checks, each sees the other's flag up and waits for it to drop, but neither flag drops until its owner gets in. Mutual exclusion holds, yet progress breaks, creating a small deadlock.

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 →