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
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: Coordinating Threads →← 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 →
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.
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 Threads
What is the difference between a thread and a process?
What is the difference between user-level and kernel-level threads?
What does pthread_join do?
Do threads share global variables?
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 →