ENع
←Threads in the kernel
Lesson 10 · Processes and threads

Threads from the kernel's side

12 min10 steps5 questionsBeginner
About this lesson

A process is one address space; a thread is one line of execution inside it, with its own registers and its own stack. What does the kernel actually keep for each thread, and what changes when a program makes a second one? Follow a short C program as pthread_create asks the kernel for a thread with clone, the scheduler runs both threads on two cores, they write into the same global array, and one thread ends while the process carries on. The lesson on the context switch and the timer interrupt shows how the kernel saves and loads registers; the Software lesson on threads and concurrency shows threads from the programmer's side, and the Linux lesson on processes and signals shows the commands.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 10 · Interactive
01 / 10

A process with one thread

A running program is a process: one address space holding its code, its global data and a stack. It starts with one thread, one line of execution. The kernel keeps a record for it, thread ID 1000.

process 1000   one address space:
                 code      the program text
                 globals   int part[2]
                 stack     for thread 1000
                 + heap, open files, signal handlers
thread 1000    one record in the kernel
               single-threaded: thread ID = process ID
Loading figure…
or ← →
Read the lesson step by step
  1. A process with one thread

    A running program is a process: one address space holding its code, its global data and a stack. It starts with one thread, one line of execution. The kernel keeps a record for it, thread ID 1000.

    process 1000   one address space:
                     code      the program text
                     globals   int part[2]
                     stack     for thread 1000
                     + heap, open files, signal handlers
    thread 1000    one record in the kernel
                   single-threaded: thread ID = process ID
  2. What a thread is

    A thread is the part that moves: a program counter saying which instruction is next, the other CPU registers, and its own stack. While it runs, its registers sit in a core. Code and globals belong to the whole process.

    per thread                 per process (shared)
      program counter (PC)       code
      registers                  globals and heap
      stack pointer (SP)         open files
      its own stack              signal handlers
      thread ID                  process ID
    
    running   registers are in a core
    not       registers are saved in its kernel record
  3. Line 1: asking for a thread

    Line 1 asks for a second thread. The C library first sets aside memory for its stack, then makes the clone system call: make a thread that shares my memory, my open files and my signal handlers.

    line 1   pthread_create(&t, 0, f, 0);
    
    the C library (glibc on Linux):
      1. sets aside a new stack   (size from ulimit -s: often 8 MB)
      2. clone(flags, new stack, ...)  a system call
    
    flags glibc passes:
      CLONE_VM       share the memory
      CLONE_FILES    share the open files
      CLONE_SIGHAND  share the signal handlers
      CLONE_THREAD   same process (thread group)
      + CLONE_FS, CLONE_SYSVSEM, CLONE_SETTLS, ...
  4. The kernel adds a record

    The kernel builds a second record, thread ID 1001. It is not a new process: it points at the same address space, so no memory is copied. Its saved stack pointer points into the new stack, its program counter at f.

    record      thread 1000          thread 1001
    thread ID   1000                 1001
    process ID  1000                 1000   (same group)
    memory      process 1000         process 1000  (shared)
    SP          stack 1000           stack 1001
    PC          in main              start of f
    state       running              ready
    
    clone returns 1001 to the caller; no memory is copied
  5. The scheduler picks threads

    The kernel's scheduler chooses threads, not processes. Thread 1001 is ready and core 1 is free, so the kernel loads its saved registers into core 1. Now both threads run at the same time.

    scheduler sees   thread 1000   running on core 0
                     thread 1001   ready
    core 1 free  ->  load 1001's registers:
                     PC = start of f, SP = stack 1001
    
    Linux (NPTL) is 1:1: each thread is its own
    kernel scheduling entity.
    With one core, they would take turns instead.
  6. Lines 2 and 3: shared memory

    Thread 1000 runs line 2 and stores 10 in part[0]. Thread 1001 runs f and stores 20 in part[1]. Both land in the same array, because both threads use one address space. Local variables stay on each thread's own stack.

    core 0  thread 1000   part[0] = 10;
    core 1  thread 1001   part[1] = 20; /* in f */
    
    part is a global: one copy, one address,
    seen by both threads.
    part    [10, 20]
    
    different cells, so the two writes cannot clash
  7. One process, two thread IDs

    Ask each thread who it is. getpid() answers 1000 in both: one process. gettid() answers 1000 and 1001: two threads. On Linux a process is a thread group, and its process ID is the ID of its first thread.

                  getpid()   gettid()
    thread 1000   1000       1000
    thread 1001   1000       1001
    
    getpid() returns the thread group ID (TGID)
    /proc/1000/status   Tgid: 1000   Threads: 2
    /proc/1000/task/    1000  1001
  8. Line 4: waiting

    Line 4 waits for thread 1001 to finish. If it is still running, thread 1000 sleeps: the kernel saves its registers into its record and frees core 0 for any other ready thread.

    line 4   pthread_join(t, 0);
    
    thread 1001 not done yet ->
      thread 1000 sleeps in the kernel (a futex wait)
      its PC, SP and registers -> its record
      core 0 is free
    
    record 1000   state sleeping
  9. Thread 1001 ends

    Thread 1001 returns from f, which ends only that thread. The kernel removes its record and wakes thread 1000, which goes back on a core. part[0] + part[1] is 30. The process and its memory carry on.

    f returns   = pthread_exit for thread 1001 only
    kernel      removes record 1001, frees core 1
                zeroes a word the C library watches and
                does a futex wake (CLONE_CHILD_CLEARTID)
    thread 1000 woken, back on core 0
                printf -> 30
    
    process 1000 still has its memory and part
  10. Why threads?

    A new thread copies no memory, and switching between two threads of one process keeps the same page table. The catch: shared memory means threads can trip over each other, which the synchronisation module tackles.

    the same program in Python (real threads):
    
    import os, threading
    
    part = [0, 0]                    # a global: shared by every thread
    who = {}
    
    def f():                         # thread 2 starts here
        part[1] = 20
        who["f"] = (os.getpid(), threading.get_native_id())
    
    t = threading.Thread(target=f)
    t.start()                        # the kernel makes a new thread
    part[0] = 10
    who["main"] = (os.getpid(), threading.get_native_id())
    t.join()                         # wait for thread 2 to finish
    print(part[0] + part[1])
    print("same process:", who["main"][0] == who["f"][0])
    print("two threads:", who["main"][1] != who["f"][1])
    
    prints:
    30
    same process: True
    two threads: True

Quiz Unlocks after the last step.