CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 1 of 7 · 1 min read

Why this page comes fourth

In this module you will

  • Explain with a trace why two threads incrementing one counter lose updates.
  • Run a program that shows lost updates and fix it with a lock.
  • Say what makes a function thread-safe and name safe replacements for strtok and localtime.
  • Use __thread and know why errno is private to each thread.
  • Apply the rule "share less" when designing threaded code.

Pages 1 to 3 showed what threads are and how they run. The price of sharing an address space is that two threads can change the same variable at the same time. This page shows what goes wrong, with real runs, and the first tools against it. Level 4 covers the full story of locks, semaphores and condition variables, and this page only gives the minimum needed to write correct threaded programs from here on. The main sources are "The Linux Programming Interface" (TLPI), chapters 29 to 31, "Operating Systems: Three Easy Pieces" (OSTEP), chapters 26 and 28, and "Operating System Concepts" (OSC), chapters 4 and 6. All programs were compiled with gcc -Wall -Wextra -pthread and run on Linux.

About this example About this example

Real: The C programs, commands and outputs on this page were compiled with gcc -Wall -Wextra -pthread and run on a Linux test machine (2 processors, kernel 6.18, glibc 2.39).

Scripted: The worked traces use small numbers chosen so they can be followed by hand.

Not real: The page simplifies real systems. Actual kernels add more cases, limits and tuning than a short page can show.