Threads โ€” Easy Exam Guide Unit u05 (Threads + Pthreads). Every idea in simple words, linked to how the exam asks it. ๐Ÿ”ด = comes a lot.

Written in simple (B1) English. Read it from top to bottom before the exam.

0How "threads" come in the exam

Threads give you three kinds of questions. Most are easy true/false recall. Sometimes there is a "trace the output" program, and sometimes a bigger "write a Pthreads program" task.

The question you will seeHow oftenSection
๐Ÿ”ด True/false: thread vs process, shared vs private, user vs kernel threads, join/exit/returnmost examsยง1โ€“ยง4
๐ŸŸก Trace the output of a small program where two threads spawn each othersometimesยง6
๐ŸŸก Write a Pthreads program (e.g. threaded Fibonacci, mutual spawning) โ€” worth 5โ€“6 pointssometimesยง3 + drills
โš ๏ธ Remember
The true/false questions take points away for wrong answers. Many traps use the word "always" or "in any case" โ€” these are usually false.

1What a thread is, and what it shares ๐Ÿ”ด comes a lot

A process groups resources. A thread is one flow of execution inside a process โ€” it is the unit the CPU schedules. A thread is a "lightweight process": making a thread is 10โ€“100ร— faster than making a process.

One process can have many threads. They all run in the same memory, so they share data automatically. There is no parent/child between threads โ€” all threads are equal.

Shared by all threadsPrivate to each thread
code ยท global & static variables ยท the heap ยท open files ยท signalsthe stack (local variables) ยท CPU registers ยท the program counter
๐ŸŽฏ In the exam
TRUE: threads share global variables (so they can communicate through them); a write to a global by one thread is seen by all; threads have no parent/child. Because they share memory without protection, you need synchronization (mutex/semaphore) โ€” see u07.
โœ— Trap sentences (FALSE)
  • "Each thread has a parent (like processes)." No โ€” threads are equal, no hierarchy.
  • "Two threads writing the same variable can cause a deadlock." No โ€” that is a race condition, not a deadlock.
  • "Using more threads always makes a program faster." No โ€” overhead and serial parts can cancel the gain.

2User-level vs kernel-level threads ๐Ÿ”ด comes a lot

User-level threadsKernel-level threads
Who manages thema library, in user spacethe kernel (the OS)
Does the OS know them?No โ€” the OS sees only the processYes โ€” the OS keeps a table of all threads
Speedfaster (no switch to kernel mode)slower (kernel-mode switch each time)
If one thread does a blocking callthe whole process blocks (all its threads stop)other threads can keep running
True parallelism on many cores?No by itselfYes

Mapping models: many-to-one (many user threads โ†’ 1 kernel thread = the user model), one-to-one (each user thread โ†’ its own kernel thread; Linux NPTL works like this), and many-to-many / hybrid (m user โ†’ n kernel, n < m). Almost all modern systems have kernel threads.

๐ŸŽฏ In the exam (2023-06-15 Ex8, 2025-02-17 Ex6)
TRUE: the kernel keeps a global table only of kernel threads; user threads can be far more numerous and are multiplexed onto fewer kernel threads; user-level switching is cheaper.
โœ— Trap sentences (FALSE)
  • "It is always better to use kernel threads." No โ€” it depends on the work.
  • "The OS keeps a table of user threads." No โ€” it does not know them.
  • "Pure user threads can run in parallel on many cores." No โ€” the kernel sees one schedulable entity.
  • "There is typically one kernel thread per user thread." No โ€” usually fewer kernel threads.

3The Pthreads API ๐Ÿ”ด needed for code & trace

Include <pthread.h> and compile with -lpthread. A thread is just a function that runs at the same time as main. The thread id has type pthread_t (you cannot print or compare it directly โ€” use the functions).

int  pthread_create(pthread_t *tid, const pthread_attr_t *attr,
                    void *(*startRoutine)(void *), void *arg);
//   make a thread that runs startRoutine(arg). attr=NULL โ†’ default. arg=NULL if none.
//   returns 0 on success.

int  pthread_join(pthread_t tid, void **valuePtr);
//   wait for thread 'tid' to finish; valuePtr receives its return value (NULL to ignore).

void pthread_exit(void *valuePtr);   // end THIS thread, give back valuePtr
int  pthread_detach(pthread_t tid);  // detach: no one can join it
pthread_t pthread_self(void);        // id of the calling thread
Pattern for the write-code questions
To make a recursive algorithm parallel: each recursive call becomes a new thread. Create the children with pthread_create, then pthread_join each one and add the results (passed back through pthread_exit). See the threaded Fibonacci in the drills.

4exit() vs pthread_exit() vs return ๐Ÿ”ด comes a lot

This is a favourite true/false question. The rule:

ActionEffect
exit() (by any thread)ends the WHOLE process โ€” all threads die
return from mainends the whole process
return from a normal thread functionends only that thread
pthread_exit()ends only the calling thread (others keep running)
Nice trick
If main calls pthread_exit(NULL) instead of return, the other threads keep running even though main is done.
โœ— Trap sentences (FALSE)
  • "return in a thread in any case ends the whole process." No โ€” only from main.
  • "All other threads end when one thread calls pthread_exit." No โ€” only that thread ends.

5Passing arguments โ€” the &i race ๐ŸŸก a known trap

A classic bug: in a loop, you pass the address of the loop variable to each thread.

for (i = 0; i < N; i++)
    pthread_create(&t[i], NULL, tF, (void *)&i);   // BUG: same address &i for all

All threads get the same address. While they read it, main keeps changing i. So the threads read the wrong value โ€” very often they all read the final value (e.g. N).

How to pass arguments correctly

๐ŸŽฏ In the exam (2022-02-10 Ex7)
If the code passes &i: TRUE that "the value can be 10 (the final value) for one thread" and even "10 for all threads". FALSE that "each thread gets a different value" or "a copy of i is passed" (an address is passed, not a copy).

6Reading thread programs (output trace) ๐ŸŸก sometimes

These look hard but follow one rule: each thread does pthread_create then pthread_join right away. Because it joins immediately, it waits for its child before going on โ€” so the program runs almost like a single line (serial), not really in parallel.

โ–ถ Method
  1. Two functions (say T1, T2) call each other. Follow them as one chain.
  2. Each step changes n (e.g. n-=2) and prints, then spawns the other and joins it.
  3. Watch where the value is printed: before or after the change. With n-- the old value prints; with --n the new one.
  4. The chain stops when the base condition (n>0) fails.
Example (2022-09-06 Ex7, start 5; T1 does n-=2 then prints (n); T2 does n+=1 then prints [n]):
(3) [4] (2) [3] (1) [2] (0)

7One-page trap sheet

  • Threads share: code, globals/statics, heap, open files. Private: stack, registers, program counter.
  • No parent/child between threads. Concurrent writes to a global = race condition (not deadlock).
  • "Always faster with more threads" / "always better to use kernel threads" โ†’ FALSE.
  • User threads: faster, but a blocking call blocks the whole process; no real multi-core parallelism alone.
  • Kernel threads: OS keeps a global table; one-to-one or many-to-many; can run in parallel.
  • exit() = whole process dies. pthread_exit() / return = only that thread (return only from its start function; from main it ends the process).
  • pthread_join(tid, &ret) waits a specific thread and reads its return value. Detached threads can't be joined.
  • Passing &i in a loop = bug (all read the same, often the final value). Pass an own array element or a struct.
  • In trace programs, create+join means it runs serially; follow the chain and watch n-- vs --n.