Interrupts and Atomic Operations, Explained

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

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

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

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.

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 Interrupts and Atomic Operations

What is a race condition?
A race condition is a bug where the result depends on the exact timing of threads touching shared data. A line like sold = sold + 1 is really three steps: load, add, and store. If two threads both load 5, both add 1, and both store 6, one update is lost. Totals can come out short, and by a different amount on each run.
What is an atomic operation?
An atomic operation is one the hardware carries out as a single, indivisible step, so no other thread can slip into the middle. Since C11, standard C offers atomic types in the header stdatomic.h, and atomic_fetch_add does the load, add, and store as one unit without a lock. The word atomic comes from the Greek for cannot be cut.
When should a mutex be used instead of an atomic variable?
Use a mutex when two or more variables must change together, and an atomic for a single counter or flag. An atomic protects only the one operation given to it. If each sale atomically adds to a cake count but updates a money total with a plain add, the cake count stays exact while the money total comes up short.
What is the difference between an interrupt and a signal?
An interrupt is a signal sent to the CPU by hardware, such as the keyboard, a network card, or the timer, while a signal in this sense is a short software message the kernel delivers to a process. When a handler is in place, both stop the current work, run it, and then resume where they left off. Pressing Control-C, for example, sends SIGINT, which ends a process by default unless it installs a handler.

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 →