Threads, Explained | Introduction to Operating Systems

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

Threads

Introduction to Operating Systems · Chapter 2: Process Management: Scheduling, Multitasking, and System CallsSection 2.8 · lesson 17 of 837 min · free with a free account

← Preemptive SchedulingNext lesson: Coordinating Threads →

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 threads share one process and how pthreads starts and joins them.

  • Define a thread and list what it owns and what it shares
  • Explain four benefits of using threads
  • Compare user-level threads with kernel-level threads
  • Use pthread_create and pthread_join to start threads and wait for them

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

Opening Question

One Web Page, Many Things at Once

Sam, who runs a small online bakery, opens the shop's web page. It keeps scrolling smoothly while a picture of a cake loads. Meanwhile, a counter updates the basket total, and a chat box waits for a customer's question. It's one program, yet it does many things at once. If it were a single worker, the page would freeze at every slow step. Instead, it uses threads: several workers inside the same program, sharing one kitchen.

Definition

One Line of Execution in a Process

A thread is one line of execution inside a process. It has its own place in the code, its own registers, and its own small stack for function calls. Nothing else is its own. All the threads of a process share the same code, the same global variables, and the same open files. That's why a thread is called lightweight. Starting one, or switching between two, is far cheaper than doing the same for whole processes, which each need private memory.

Analogy

Bakers Sharing One Kitchen

Picture a bakery kitchen. The process is the whole kitchen, with its ovens, its flour and its recipe books. Threads are the bakers working in it. They share the ovens and the flour, but each one is at a different step, with their own apron and bowl. Your computer is full of examples. A word processor checks spelling in one thread while you type in another. A browser may draw the page in one thread, and download images in another, so a slow download never freezes the window.

Benefits

Responsiveness, Sharing, Economy, and Scaling

Why use threads at all? Responsiveness: one thread keeps the window alive while another loads a picture. Sharing: threads read the same data, without copying it between processes. Economy: creating a thread costs far less than creating a process. And scaling: on a computer with several cores, the threads of one program can run on different cores at the same time, so work that splits well finishes sooner.

Common Mistake

Threads Share Memory

A common mistake is thinking threads are separate programs that can't touch each other, the way processes can't. Threads share memory. That's their strength, and their danger: two threads changing the same variable at once can corrupt it. Lesson 3.3 shows the problem. The program in this lesson avoids it, by giving each thread its own slot to write to.

Thread Models

User-Level Versus Kernel-Level Threads

Who manages the threads? User-level threads are created and scheduled by a library inside the program. The operating system doesn't know they exist. It sees one process. Switching between them is very cheap, because no system call is needed. But if one thread makes a blocking call, like waiting for the disk, the whole process sleeps. Every thread stops, and one process can't use several cores. Kernel-level threads are known to the operating system, which schedules each one like a process. A thread that blocks doesn't stop its siblings, and threads can share out the cores. Creating and switching them goes through the kernel, so it's slower, but still lighter than processes. Linux, Windows and macOS all use kernel threads for their standard thread libraries.

Worked Example

Three Shifts With Pthreads

On Linux and macOS, C programs create threads with the POSIX threads library, called pthreads. This program works out Sam's muffin income for three shifts. The muffins sold in each shift are in the sold array. Each thread handles one shift, and writes its income into its own slot of the total array. main starts the three threads with pthread create, handing each one its shift number. Then it calls pthread join on each, which means: wait here until that thread has finished. Only after all the joins does it print, one shift at a time.

Running It

Join First, Then Print

Why print after the joins? Threads take different times to run, so printing from inside them could scramble the order. Joining first makes the output the same on every run. Build it with dash pthread, the usual flag for thread programs, and run it. Shift one: twelve muffins, thirty-six dollars. Shift two: seven and twenty-one. Shift three: twenty and sixty. No two threads touched the same slot, so they couldn't interfere. Yet they shared both arrays, with no copying at all.

Good Habit

Always Join the Threads You Start

One habit to keep: always join the threads you start. If main returned while threads were still working, the whole process would end, and the threads would be cut off mid-job. That bug shows up only sometimes, which makes it hard to find.

Quick Check

Ten Loaves Minus Four

Quick check, with a new program. A global variable, loaves, starts at ten. One thread runs sell, which takes away four. main joins that thread, then prints loaves. What does main print? Pause, and decide. Six loaves. Threads share their process's memory, so when the sell thread took away four, it changed the one and only loaves, and main sees the change. Ten is the tempting answer: in lesson 2.2, the parent still saw ten after its forked child sold four. But fork copied the memory. A thread gets no copy. And the join makes six certain: main reads loaves only after the thread has finished.

Key Takeaways

Shared Kitchen, Separate Stacks

To recap. A thread is one line of execution inside a process, with its own stack, registers and program counter. Threads share their process's code, globals and open files, which makes them cheap, and makes sharing data easy and risky. User-level threads are managed by a library. Kernel-level threads are scheduled by the operating system, and can use several cores. And pthread create starts a thread, while pthread join waits for it to finish.

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 Threads

What is the difference between a thread and a process?
A process has its own private memory, while a thread is one line of execution inside a process that shares the process's code, global variables, and open files with its sibling threads. Each thread keeps only its own program counter, registers, and stack. That makes threads cheaper to create and switch than processes, and it makes sharing data both easy and risky.
What is the difference between user-level and kernel-level threads?
User-level threads are created and scheduled by a library inside the program, so the operating system sees only one process. Switching them is very cheap, but one blocking call stops every thread, and they cannot use several cores. Kernel-level threads are scheduled by the operating system, so a blocked thread does not stop its siblings and threads can run on different cores.
What does pthread_join do?
The pthread_join function makes the calling thread wait until a specific thread has finished. A main function typically starts threads with pthread_create and then joins each one before using their results or returning. If main returned while threads were still working, the whole process would end and cut them off mid-job, a bug that shows up only sometimes.
Do threads share global variables?
Yes, all threads of a process share the same global variables, so a change made by one thread is seen by the others. If a global starts at 10 and a thread subtracts 4, main prints 6 after joining that thread. A forked child process is different: it gets its own copy of memory, so the parent would still see 10.

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 →