UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 3.3 Free with a free account
Interrupts and Atomic Operations
Introduction to Operating Systems · Chapter 3: Concurrency, Synchronization, and Deadlock PreventionSection 3.3 · lesson 20 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: Mutual Exclusion →← Synchronization ToolsNext lesson: Mutual Exclusion →
A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →
In this lesson
How lost updates happen and how locks, atomics, and interrupts relate.
- Explain why a single increment is three CPU steps that can interleave
- Fix a race condition with a mutex or an atomic operation
- Explain why an atomic protects only one operation
- Describe interrupts, interrupt handlers, and signals
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 (931 words). Read along, or search it.
Opening Question
Two Hundred Thousand Sales Come Up Short
Sam, who runs a small online bakery, counts the cakes the shop sells. Two threads run two checkout lanes, and each does one tiny job: add one to a shared total. In this test, each lane adds one, a hundred thousand times. So the total should be two hundred thousand. Build it, and run it. The total comes up short. Run it again: short again, and by a different amount. Nobody deleted anything. Some additions simply vanished. This lesson shows how that happens, and how the operating system and the hardware stop it.
Three Steps
Load, Add, and Store
The line, sold equals sold plus one, looks like one action. To the CPU, it's three. Load the number from memory into a register. Add one, in the register. And store the result back to memory. A thread can be paused between any two of those steps, and another thread may run all of its steps in the gap.
Worked Example
One Unlucky Schedule Replayed
Here's one unlucky schedule, replayed step by step in Python. It replays one chosen order, not a live race, so it prints the same thing every time. The total starts at five. Thread A loads five into its register. Then the scheduler switches, and B loads five too. A adds one: its register holds six. B adds one: its register holds six as well. A stores six. Then B stores its six, right on top. Two additions happened, yet the total rose by one. A's update was lost. That's a race condition: the answer depends on timing.
Race Results
A Different Wrong Total Each Run
A real program with no lock hits this at different places on every run. That's why the race dot c totals didn't match each other. So there's no single wrong number to quote. There's only the rule: the total can be wrong, and it can differ between runs.
First Fix
Locking the Counter
The first fix is the lock from lesson 3.2. Declare a mutex, and put the three steps between lock and unlock. Now no thread can start its load until the other has finished its store. Rebuild, and run it: two hundred thousand. Run it again: two hundred thousand. With the lock, it's exact on every run.
Second Fix
An Indivisible Fetch and Add
The second fix is an atomic operation: one the hardware carries out as a single, indivisible step, so no other thread can slip into the middle. The word comes from the Greek for: cannot be cut. Since C11, standard C has atomic types, in the header std atomic dot h. Here the total is an atomic long, and atomic fetch add does the load, the add, and the store as one unit. There's no lock, and no waiting. Build it and run it: two hundred thousand again.
Quick Check
Sold Is Exact, Cents Falls Short
Quick check. Each sale now does two things. It adds one cake to sold. And it adds two hundred fifty cents to cents. Two lanes, a hundred thousand sales each. Pause and predict: which total can come out wrong? Only the money, cents. Run it: sold is exact, and cents comes up short. Run it again, and it's short by a different amount. An atomic protects only the one operation you give it. The plain cents update is still a load, an add and a store, and the threads cut into it. So it isn't both. For a single counter or flag, an atomic is simple and fast. When two or more variables must change together, use a mutex.
Definition
Hardware Signals That Demand Attention
So far, the interruption came from the scheduler pausing a thread. But real systems are interrupted all the time, and the word has a precise meaning. An interrupt is a signal sent to the CPU by hardware, like a keyboard, a network card, or the timer, that says: stop, something needs attention. The CPU saves its place, runs a short piece of kernel code called an interrupt handler, and then goes back to the interrupted work, as though nothing had happened.
Interrupt Danger
Handlers Touching Shared Data
Interrupts are a danger for shared data too. If a handler and the main code touch the same variable, the handler can strike between the load and the store, just like thread B. On a system with a single CPU, a simple kernel fix is to switch interrupts off briefly around a critical step, so the step can't be cut. That doesn't help with several cores, because the other cores keep running. There, atomic instructions and locks do the job.
Signals
The Software Cousin of an Interrupt
A signal is the software cousin of an interrupt: a short message the kernel delivers to a process. Pressing Control C sends one called SIGINT. A process can register a handler for a signal. This program installs one for SIGUSR1, then sends that signal to itself, with raise. The handler only sets one flag. Its type, volatile sig atomic t, is one that C guarantees can be written safely during a signal. Run it. The handler ran, and the program carried on right where it left off.
Real Example
Boring, Exact Totals
Back to Sam's test. Ivy, who looks after the computers at a school, ran it, got a total that was too low, ran it again, and got a different low total. A bug that changes its answer is a race, she said. She wrapped the counter in a lock, and every run printed the same exact number. Boring, Sam said, happily.
Key Takeaways
Lost Updates and Their Fixes
To recap. One line like sold plus one is three CPU steps: load, add, and store. Two threads cutting into those steps lose updates, and the total varies from run to run. Fix it with a mutex, or with one atomic operation, which protects only that operation. And interrupts and signals stop the work, run a handler, then resume where it left off.
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 Interrupts and Atomic Operations
What is a race condition?
What is an atomic operation?
When should a mutex be used instead of an atomic variable?
What is the difference between an interrupt and a signal?
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 →