Multithreading and POSIX Threads
Overview
This week introduces threads as lightweight units of execution within a process.
Students will learn how threads differ from processes, how they share resources, and how to use the POSIX Threads (pthreads) API to create, synchronize, and manage them effectively in Linux.
Key Concepts
-
Threads vs. Processes
- A process has its own memory space; threads share the same address space.
- Threads enable concurrent execution within a single process.
- Threads are more efficient for parallel tasks that share data.
-
POSIX Threads (pthreads)
- Standardized API for thread programming in UNIX/Linux environments.
- Main functions:
pthread_create()— create a new threadpthread_join()— wait for a thread to completepthread_exit()— terminate the current threadpthread_self()— obtain the thread IDpthread_detach()— run thread independently (nojoin)
-
Thread Lifecycle
- States: new → runnable → running → terminated
- Resource management: stack, thread ID, attributes
- Detached vs. joinable threads and their memory implications
-
Thread Safety
- Shared memory requires careful access to avoid conflicts (to be covered later).
- Distinguish between thread-safe and non-thread-safe library functions.
Practice
Thread Creation
- Write a simple program that spawns multiple threads using
pthread_create(). - Pass arguments to threads and print thread identifiers with
pthread_self().
Joining and Detaching
- Use
pthread_join()to synchronize thread completion. - Create detached threads using
pthread_detach()and observe behavior.
Thread Attributes
- Experiment with
pthread_attr_tto set stack size or detach state. - Observe resource usage differences using tools like
htop(Shift + H).
Observation
- Compare thread vs. process creation times using
timeand simple benchmarks.
Homework
Samples
References
Required
- Function Pointer in C
- ECE 252 Lecture 10: Threads
- ECE 252 Lecture 11: Threads and Concurrency
- Параллельное программирование. Лекция 1 (RUS)
- Introduction to Pthreads
- Advanced Programming in the UNIX Environment — W. Richard Stevens, Chapter 11 “Threads”
- Programming with POSIX Threads — David R. Butenhof
- Operating Systems: Three Easy Pieces — Chapter on “Concurrency and Threads”
- The Open Group — POSIX Threads Specification
Recommended
- Linux manual page - pthread_create(3)
- Linux manual page - pthread_join(3)
- Linux manual page - pthread_exit(3)
- Linux manual page - pthread_cancel(3)
- Linux manual page - pthread_attr_init(3)
- Linux manual page - pthread_attr_destroy(3)
- Multithreading in C
- Thread functions in C/C++
Quiz (Self-Check)
- What is the key difference between a process and a thread?
- Which function is used to create a new thread in POSIX?
- What happens if a joinable thread finishes without being joined?
- What is the purpose of
pthread_detach()? - Why do threads share the same memory space, and what are the implications of this?
- What information does
pthread_self()return?