CPS 356 & 444/544 Lecture notes: Threads & Thread-safe Functions

Coverage: [OSCJ8] Chapter 4 (pp. 153-192), and [USP] Chapter 2 (pp. 21-23, 38-48)


(ref. [OSIDP] Fig. 4.1 on p. 162; image courtesy [OSIDP] webpage)


A thread is
  • an ADT within a process
  • has its own stack, program counter value, register set, and state
  • share process resources

  • (heavyweight) process vs. (lightweight) thread

  • We also have a thread control block (TCB).

    Relationship between process and thread states

    (ref. [OSIDP] Fig. 4.7 on p. 170; image courtesy [OSIDP] webpage)
  • variables are either static (exist for the life of the process) or automatic (allocated/deallocated on block entry/exit)

  • Synchronization

    Thread-safe functions

    • static variables make the use of multiple threads unsafe
    • strtok is not thread-safe because it uses a static pointer index into the string being tokenized (e.g., wordcount, wordaverage)
    • use POSIX thread-safe function strtok_r (_r stands for reentrant)
    • moral of the story: avoid using static storage


      [OSCJ8] A. Silberschatz, P.B. Galvin, and G. Gagne. Operating Systems Concepts with Java. John Wiley and Sons, Inc., Eighth edition, 2007.
      [OSIDP] W. Stallings. Operating Systems: Internals and Design Principles. Prentice Hall, Upper Saddle River, NJ, Sixth edition, 2009.
      [USP] K.A. Robbins and S. Robbins. UNIX Systems Programming: Concurrency, Communication, and Threads. Prentice Hall, Upper Saddle River, NJ, Second edition, 2003.

    Return Home