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 see | How often | Section |
|---|---|---|
| ๐ด True/false: thread vs process, shared vs private, user vs kernel threads, join/exit/return | most exams | ยง1โยง4 |
| ๐ก Trace the output of a small program where two threads spawn each other | sometimes | ยง6 |
| ๐ก Write a Pthreads program (e.g. threaded Fibonacci, mutual spawning) โ worth 5โ6 points | sometimes | ยง3 + drills |
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 threads | Private to each thread |
|---|---|
| code ยท global & static variables ยท the heap ยท open files ยท signals | the stack (local variables) ยท CPU registers ยท the program counter |
- "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 threads | Kernel-level threads | |
|---|---|---|
| Who manages them | a library, in user space | the kernel (the OS) |
| Does the OS know them? | No โ the OS sees only the process | Yes โ the OS keeps a table of all threads |
| Speed | faster (no switch to kernel mode) | slower (kernel-mode switch each time) |
| If one thread does a blocking call | the whole process blocks (all its threads stop) | other threads can keep running |
| True parallelism on many cores? | No by itself | Yes |
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.
- "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
- A thread function gets one argument (a
void*) and returns avoid*. - You return a result either with
return value;orpthread_exit(value). The joiner gets it through thevoid**ofpthread_join. - Joinable thread = someone can
pthread_joinit and read its result. Detached thread = nobody can join it; joining it fails (EINVAL/ESRCH).
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:
| Action | Effect |
|---|---|
exit() (by any thread) | ends the WHOLE process โ all threads die |
return from main | ends the whole process |
return from a normal thread function | ends only that thread |
pthread_exit() | ends only the calling thread (others keep running) |
main calls pthread_exit(NULL) instead of return, the other threads keep running even though main is done.- "
returnin a thread in any case ends the whole process." No โ only frommain. - "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
- Own array element:
tA[i]=i; pthread_create(&t[i],NULL,tF,(void*)&tA[i]); - A per-thread struct (one element per thread).
- "Dirty" but works: cast the value into the pointer (
(void*)(long)i), and cast back inside the thread.
&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.
- Two functions (say T1, T2) call each other. Follow them as one chain.
- Each step changes
n(e.g.n-=2) and prints, then spawns the other and joins it. - Watch where the value is printed: before or after the change. With
n--the old value prints; with--nthe new one. - The chain stops when the base condition (
n>0) fails.
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; frommainit ends the process).pthread_join(tid, &ret)waits a specific thread and reads its return value. Detached threads can't be joined.- Passing
&iin 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.