Skip to content
System Programming
Threads

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 thread
      • pthread_join() — wait for a thread to complete
      • pthread_exit() — terminate the current thread
      • pthread_self() — obtain the thread ID
      • pthread_detach() — run thread independently (no join)
  • 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_t to set stack size or detach state.
  • Observe resource usage differences using tools like htop (Shift + H).

Observation

  • Compare thread vs. process creation times using time and simple benchmarks.

Homework


Samples


References

Required

Recommended


Quiz (Self-Check)

  1. What is the key difference between a process and a thread?
  2. Which function is used to create a new thread in POSIX?
  3. What happens if a joinable thread finishes without being joined?
  4. What is the purpose of pthread_detach()?
  5. Why do threads share the same memory space, and what are the implications of this?
  6. What information does pthread_self() return?