Coordinating Threads, Explained

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

Coordinating Threads

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

← ThreadsNext lesson: Synchronization Tools →

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

Why threads sharing data need rules, and which tool fits which problem.

  • Explain why the scheduler's interleaving makes thread coordination necessary
  • Distinguish shared data from private data within a process
  • Identify race conditions, deadlocks, and ordering problems and the tool for each
  • Decide whether a given program needs a lock

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

Opening Question

Two Bakers, One Mixing Bowl

Two bakers reach for the same mixing bowl at the same moment. One pours in flour. The other already has eggs in her hands, and the batter is ruined. Nobody was careless. They simply had no rule for taking turns. Threads inside a program meet this problem thousands of times a second. So who supplies the rules, and what do the rules look like?

Why Rules Matter

The Scheduler Ignores What Threads Do

One baker never has this problem. Two bakers sharing one kitchen do. In a computer, the bakers are threads, and the kitchen is the process they live in. The CPU scheduler, from lesson 2.6, decides which thread runs and when. With several cores, two threads can even run at the very same instant. And the scheduler works for speed, not for politeness. It may pause a thread in the middle of a job, and it has no idea what the thread is doing with its data. So coordination means the rules, supplied by the operating system and the programmer, that make several threads work together safely, and in a sensible order.

Timing Bugs

Right on Monday, Wrong on Tuesday

Without those rules, a program can give the right answer on Monday and a wrong one on Tuesday, with no change at all to the code. Programmers have a nickname for a bug that vanishes when you try to watch it, because watching changes the timing. It's called a heisenbug, after the physicist Heisenberg. Timing bugs between threads are the classic cause.

Shared Versus Private

Globals Shared, Locals Private

Not everything threads touch is dangerous. Each thread keeps its own local variables on its own stack, and nobody else sees them. That's private data. Everything else in the process is shared data: global variables, memory on the heap, and open files. There's one copy, and every thread sees it. A small C test on a Mac shows the difference. Two threads each note where they found a global variable, and where they found a local one. The two notes for the global match: one shared copy. The two notes for the local differ: each thread has its own. Risk lives only in shared data that somebody changes. Data that's only read, or that's private, needs no rules.

Common Mistake

One Small Variable Is Enough

A common mistake is to think one little variable can't hurt. Size doesn't matter. A single shared integer that two threads update is enough to lose data, and lesson 3.3 shows it happening with a real counter.

Interleaving

Same Program, Different Orders

Because the scheduler can switch threads at almost any moment, the same program can run in different orders. Say two threads each take three steps. In run one, thread A finishes all three before B starts. In run two, the scheduler cuts in, and the steps interleave: A, B, A, B. Neither run is a bug by itself. It becomes a bug when the answer depends on which run you got.

Real Example

A Crash Once a Week

Sam, who runs a small online bakery, had a shop program that crashed about once a week, with no pattern. Ivy, who looks after the computers at a school, read the code. Two threads update the stock count, she said. Most days one finishes before the other starts, so nobody notices. So the bug only shows up when the timing is unlucky? Right, said Ivy. Those are the worst kind. Let's add a lock.

Three Troubles

Races, Deadlocks, and Ordering

Three kinds of trouble follow from all this, and each one has its own tool. A race condition is when the result depends on the exact timing of threads, as they touch shared data. The tool is a lock, or an atomic action. A deadlock is when threads wait for each other forever, each holding something the other needs. The tools are the rules in lesson 3.5: prevent it, avoid it, or detect it. And ordering is when one thread must wait for another to finish a step first, like: don't open the shop before the cake is baked. The tool for that is a semaphore, or a condition variable.

Quick Check

Which Program Needs a Lock

Quick check. Here are three small programs, and only one of them needs a lock. In the first, four threads only read one shared price list. In the second, two threads each count visitors into their own local tally, and main adds the tallies after joining them. In the third, one thread rewrites the price list while the others read it. Pause, and decide. The third one, C. Only one thread writes, but one writer is enough. A reader can catch the list half rewritten, with some prices old and some new. In A, the price list is shared, but nobody changes it, and reading can't spoil a value. And in B, the tallies are private. No two threads touch the same data while they run, so no rule is needed.

Key Takeaways

Shared, Changing Data Is the Risk

To recap. Threads share one process, and the scheduler can interleave them at any moment. The risk is shared data that someone changes. Private data and read-only data are safe. A timing-dependent result is a bug, even when most runs look fine. And each trouble has its tool: a lock or atomic for races, the deadlock rules, and semaphores or condition variables for order.

Try It

Coordination Rules at Home

Something to try. List three things at home that two people might use at once, like a bathroom, a charger, or a pan. For each, write down the rule you already use, such as a closed door, or a my-turn rule. You've just designed coordination.

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 Coordinating Threads

What is a heisenbug?
A heisenbug is a bug that vanishes or changes when you try to observe it, because watching the program changes its timing. The nickname plays on the name of the physicist Werner Heisenberg. Timing bugs between threads are the classic cause, since the same code can give a right answer on one run and a wrong one on the next without any change.
Which data is shared between threads and which is private?
Each thread's local variables live on its own stack and are private, while global variables, heap memory, and open files are shared by every thread in the process. Only shared data that some thread changes creates risk. Data that is read-only, or private to one thread, needs no coordination rules, because reading cannot spoil a value.
Does shared data need a lock if only one thread writes to it?
Yes, one writer is enough to cause trouble when other threads read the same data at the same time. A reader can catch a shared price list halfway through being rewritten, seeing some old prices and some new ones. Shared data that nobody changes, or data private to each thread, needs no such rule, because there is nothing to catch half finished.
What kinds of problems can happen when threads share data?
Three main kinds of trouble arise. A race condition is a result that depends on the exact timing of threads touching shared data, fixed with a lock or an atomic action. A deadlock is threads waiting for each other forever, handled by prevention, avoidance, or detection. An ordering problem is one thread needing another to finish a step first, solved with a semaphore or condition variable.

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 →