SyntaxPilot
Courses/CS Fundamentals for Placements/Lesson 20

CS Fundamentals for Placements · Lesson 20 of 90 · 15 min

Threads and multithreading models

threadthread control blockwhat threads share vs keep private (stack, registers, PC)benefits of threadsuser-level vs kernel-level threadsmany-to-oneone-to-onemany-to-many modelspthread_create and pthread_joinJava threadsthread poolconcurrency vs parallelismmultithreading vs multiprocessinggreen threads

These are the notes for CS Fundamentals for Placements, episode 20. In episode 19 processes talked through pipes, queues and shared memory: it worked, but it was a lot of work. Today you invent a lighter way: threads, several flows of execution inside one process. You will meet the thread, the thread control block (TCB), what threads share and what they keep private (stack, registers, program counter), the benefits of threads, user-level vs kernel-level threads, the many-to-one, one-to-one and many-to-many models, pthread_create and pthread_join, Java threads, thread pools, concurrency vs parallelism, multithreading vs multiprocessing, green threads, thread safety and reentrant functions. Every term is explained in plain words the first time it appears, and there is a full glossary at the end.

All outputs below are real: C programs were compiled with gcc -O2 (gcc 13.3, glibc 2.39) and Java with OpenJDK 21.0.12, run on Linux x86-64 with 2 CPU cores on 30 October 2026, with standard output going to a pipe as in the SyntaxPilot compiler. Times are rounded to 0.1 s. Race-condition results and memory addresses change on every run.

The six problems

Problem What it teaches
One worker is too slow Threads, why not processes, pthread_create, pthread_join
What do threads share? Shared vs private, stack, registers, PC, TCB, benefits, concurrency vs parallelism, multithreading vs multiprocessing
Who runs the threads? User-level vs kernel-level threads, green threads, many-to-one / one-to-one / many-to-many
Threads in Java Thread, start() vs run(), thread pools, virtual threads
Sharing goes wrong Lost updates, race condition, thread safety, mutex
A function with a memory Hidden state, reentrant functions, strtok vs strtok_r

Problem 1: one worker is too slow

Real-life example: one cook, four orders. Each dish needs one minute on the stove. One cook puts dish 1 on, stands there waiting, then starts dish 2. Four minutes for four easy dishes: most of his time is waiting. A program with a single flow of execution has the same problem: a server waiting for one slow network reply can't serve anyone else.

#include <stdio.h>
#include <unistd.h>
#include <time.h>

double now() {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + t.tv_nsec / 1e9;
}

void cook(int dish) {
    sleep(1);                       // each dish takes 1 second
    printf("dish %d ready\n", dish);
}

int main() {
    double start = now();
    for (int d = 1; d <= 4; d++)
        cook(d);                    // one after another
    printf("total: %.1f seconds\n", now() - start);
    return 0;
}

Output:

dish 1 ready
dish 2 ready
dish 3 ready
dish 4 ready
total: 4.0 seconds

sleep(1) stands for waiting (on the stove, a disk, the network). clock_gettime(CLOCK_MONOTONIC, ...) reads a clock that only moves forward, good for timing.

Why not four processes?

We could fork four children (episode 18): they would wait at the same time, about 1 s. But:

  • each child gets a full copy of the process's memory: heavy to create;
  • results come back only through IPC (pipes, shared memory, episode 19);
  • switching the CPU between processes means switching whole address spaces (the set of memory a process can see), which costs more.

What we want: many workers inside one process, sharing one memory from the start.

The fix: threads

Real-life example: many cooks, one kitchen.

In the kitchen In a process
The kitchen (one room) The process: the container that owns memory and open files
Fridge, recipe book, utensils used by every cook Shared by all threads: code, global data, heap, open files
Each cook: own hands, own place in his recipe A thread: its own program counter, registers and stack

A thread is a single flow of execution inside a process. Every process starts with one thread, the main thread, and can create more. Threads are sometimes called lightweight processes.

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

int ready[5];                       // global: shared by all threads

void *cook(void *arg) {
    long dish = (long)arg;          // each thread gets its own dish
    sleep(1);
    ready[dish] = 1;                // write straight into shared memory
    return NULL;
}

int main() {
    struct timespec a, b;
    clock_gettime(CLOCK_MONOTONIC, &a);
    pthread_t t[5];
    for (long d = 1; d <= 4; d++)
        pthread_create(&t[d], NULL, cook, (void *)d);
    for (int d = 1; d <= 4; d++)
        pthread_join(t[d], NULL);   // wait for each thread
    clock_gettime(CLOCK_MONOTONIC, &b);
    double secs = (b.tv_sec - a.tv_sec) + (b.tv_nsec - a.tv_nsec) / 1e9;
    int n = ready[1] + ready[2] + ready[3] + ready[4];
    printf("%d dishes ready, total: %.1f seconds\n", n, secs);
    return 0;
}

Output:

4 dishes ready, total: 1.0 seconds

POSIX threads (pthreads) is the standard thread library on UNIX-like systems (#include <pthread.h>; on older systems compile with -pthread).

Call Meaning
pthread_create(&t, attr, func, arg) Start a new thread that runs func(arg). t (a pthread_t) receives the thread's id; attr = options, NULL for defaults. func takes and returns a void * (a pointer to anything). Returns 0 on success.
pthread_join(t, &result) Wait for thread t to finish (like wait for processes) and optionally collect its return value.
pthread_exit(value) End the calling thread.
pthread_self() The calling thread's id.

Here we pass the dish number itself, cast to a pointer ((void *)d), so each thread gets its own value. The four waits overlapped, and the results came back through an ordinary global array: no pipes, no copies.

Problem 2: what do threads share?

Shared by all threads of a process Private to each thread
Code (text section) Program counter (PC): the address of its next instruction
Global and static variables (data, BSS) Registers: the values it is computing with right now
Heap (malloc / new memory) Stack: its local variables and its chain of function calls
Open files, sockets, current directory Thread id, state, priority, signal mask
Process id, user id Thread-local storage (__thread, ThreadLocal in Java)

Because each thread has its own stack, two threads can be inside different functions, or the same function with different local values, at the same time.

Thread control block (TCB)

Recall the process control block (PCB) from episode 17, the kernel's record of a process. The kernel keeps a smaller record for each thread, the thread control block (TCB): thread id, state (ready, running, blocked), saved program counter and registers, stack pointer, scheduling priority, and a pointer to its process's PCB. Switching from one thread to another saves one TCB and loads another; between threads of the same process the memory map stays, which is why it is cheaper than a process switch.

See it live

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

int shared = 0;                     // global: ONE copy for all threads
int *where[3];

void *worker(void *arg) {
    int mine = *(int *)arg;         // local: on THIS thread's own stack
    shared += mine;
    where[mine] = &mine;
    sleep(1);                       // stay alive so both stacks exist
    return NULL;
}

int main() {
    pthread_t t1, t2;
    int a = 1, b = 2;
    pthread_create(&t1, NULL, worker, &a);
    pthread_create(&t2, NULL, worker, &b);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("shared = %d (both threads changed it)\n", shared);
    printf("thread 1 local at %p\n", (void *)where[1]);
    printf("thread 2 local at %p\n", (void *)where[2]);
    return 0;
}

Output (addresses differ every run):

shared = 3 (both threads changed it)
thread 1 local at 0x7f511d5feeb4
thread 2 local at 0x7f511cdfdeb4

One global changed by both threads; two locals at different addresses, on two different stacks. (Printing those addresses after the threads ended is only for display; never use a pointer to another thread's local after it has returned.)

Benefits of threads

Benefit Meaning Example
Responsiveness One thread can wait while others keep the program reacting A download runs while the app still reacts to taps
Resource sharing Threads share memory automatically, no IPC The global ready array
Economy Creating and switching threads is cheaper than processes (no new address space) A server creating a worker per request
Scalability Threads can run on several cores at once A video encoder using all cores

Concurrency vs parallelism

Real-life example. One cook with four pans, stirring each in turn, keeps four dishes in progress: concurrency. Four cooks stirring four pans at the same instant: parallelism.

Concurrency Parallelism
Meaning Several tasks make progress over the same period, by taking turns Several tasks run at literally the same instant
Needs Even one core (the OS switches quickly) Several cores (or CPUs)
Our demo The four sleeping cooks: the waits overlapped, so 1.0 s even on one core Four threads doing heavy maths on four cores

Parallelism is one way to get concurrency; you can have concurrency without parallelism, but not the other way round.

Multithreading vs multiprocessing

Multithreading Multiprocessing
What Many threads inside one process Many separate processes
Memory Shared by all threads Each process has its own
Creation / switching Cheap Costlier
Communication Shared variables (needs locks) IPC: pipes, queues, sockets, shared memory
A crash Kills the whole process, all threads Stays inside one process
Example A game engine's render and physics threads A browser running each tab as its own process

(Careful: "multiprocessing" also names a hardware idea, a computer with several CPUs, as in episode 15. Here it means using several processes.)

Problem 3: who runs the threads?

User-level vs kernel-level threads

User-level threads Kernel-level threads
Made and scheduled by A library or language runtime inside the process The operating system kernel
Kernel sees One process (it doesn't know the threads exist) Every thread
Switching Very fast, no system call Slower: goes through the kernel
One thread makes a blocking system call The whole process blocks: every thread stops Only that thread blocks; the others run
Several cores No: the kernel gives the process one core at a time Yes
Example Classic green threads Linux pthreads, Windows threads

Green threads are threads scheduled by a runtime or virtual machine instead of the operating system (user-level threads). A blocking system call is one where the kernel makes the caller wait, like reading a file or a socket.

Multithreading models

How do user threads map onto kernel threads?

Model Mapping Good Bad Example
Many-to-one Many user threads → 1 kernel thread Fast, cheap thread switches One blocking call blocks all; only one core Classic green threads
One-to-one Each user thread → its own kernel thread True parallelism; blocking affects one thread Each thread costs a kernel thread (memory, creation time) Linux pthreads (NPTL)
Many-to-many N user threads → M kernel threads (M ≤ N) Cheap threads and parallelism Complex to implement Java 21 virtual threads

A variant of many-to-many that also lets one user thread be bound to its own kernel thread is called the two-level model.

Facts from the sources: the Linux pthreads(7) manual says NPTL (the Native POSIX Threads Library, glibc's thread implementation) and the older LinuxThreads are "so-called 1:1 implementations, meaning that each thread maps to a kernel scheduling entity". Java's virtual threads were finalized in JDK 21 (released September 2023, JEP 444); ordinary Java platform threads map one-to-one to OS threads, and many virtual threads share a platform thread.

Problem 4: threads in Java

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> {
            String me = Thread.currentThread().getName();
            System.out.println(me + " is cooking");
        };
        Thread t1 = new Thread(job, "cook-1");
        Thread t2 = new Thread(job, "cook-2");
        t1.start();                     // start() = new thread
        t1.join();                      // wait for it to finish
        t2.start();
        t2.join();
        job.run();                      // run() = no new thread!
    }
}

Output:

cook-1 is cooking
cook-2 is cooking
main is cooking
  • A Runnable is a job: an object with a run() method. () -> { ... } is a lambda, a short way to write one.
  • new Thread(job, "cook-1") wraps the job in a thread object with a name.
  • start() creates a real new thread that calls run(). join() waits for it to finish.
  • Calling job.run() directly is a normal method call on the current thread: it printed main. Only start() makes a new thread.
  • You can also extends Thread and override run(), but implementing Runnable is preferred (Java has single inheritance).

Thread pools

Problem: a busy server gets 10,000 orders a minute. A new thread per order means creating and destroying a thread every time, and thousands of live threads each need stack memory and CPU time for switching.

Fix: a thread pool: a fixed set of worker threads created once and reused. Tasks wait in a task queue; each free worker takes the next task.

import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Set<String> used = new ConcurrentSkipListSet<>();
        for (int order = 1; order <= 6; order++) {
            pool.submit(() -> {         // a task, not a thread
                used.add(Thread.currentThread().getName());
                try { Thread.sleep(200); } catch (InterruptedException e) {}
            });
        }
        pool.shutdown();                // no new tasks
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println(used.size() + " threads served 6 orders: " + used);
    }
}

Output:

2 threads served 6 orders: [pool-1-thread-1, pool-1-thread-2]

ExecutorService is Java's interface for running tasks on threads; newFixedThreadPool(2) makes a pool with 2 workers; submit queues a task; shutdown stops accepting new tasks; awaitTermination waits for queued tasks to finish. ConcurrentSkipListSet is a sorted, thread-safe set (safe to use from many threads at once).

Virtual threads (Java 21)

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        long start = System.nanoTime();
        try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10_000; i++)
                ex.submit(() -> { Thread.sleep(1000); return 0; });
        }                               // waits for all 10,000 tasks
        long sec = Math.round((System.nanoTime() - start) / 1e9);
        System.out.println("10000 virtual threads done in about " + sec + " s");
    }
}

Output:

10000 virtual threads done in about 1 s

Each task gets its own virtual thread, a cheap thread managed by the JVM. While a virtual thread sleeps or waits for I/O, the platform (OS) thread under it runs another virtual thread: the many-to-many model. The try (...) block closes the executor at the end, which waits for all tasks.

Problem 5: sharing goes wrong (thread safety)

#include <stdio.h>
#include <pthread.h>

volatile int bill = 0;              // shared; volatile: really read memory

void *add_orders(void *arg) {
    for (int i = 0; i < 10000000; i++)
        bill = bill + 1;            // read, add, write back
    return NULL;
}

int main() {
    pthread_t a, b;
    pthread_create(&a, NULL, add_orders, NULL);
    pthread_create(&b, NULL, add_orders, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("expected 20000000, got %d\n", bill);
    return 0;
}

Output (different on every run):

expected 20000000, got 10166098

volatile tells the compiler to really read and write memory each time (without it, -O2 turned the loop into a single addition and hid the bug). It does not make the code thread-safe.

Why updates get lost

bill = bill + 1 is three machine steps: read bill into a register, add 1, write it back. Two threads on two cores:

Time Thread A Thread B bill in memory
1 reads 100 100
2 reads 100 100
3 writes 101 101
4 writes 101 101

Two orders added, but the bill went up by one: a lost update. When a result depends on the exact timing of threads, it is a race condition. A piece of code that touches shared data and must not be run by two threads at once is a critical section (episode 24).

Code is thread-safe if it works correctly even when several threads run it at the same time.

Fix: a mutex

#include <stdio.h>
#include <pthread.h>

volatile int bill = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *add_orders(void *arg) {
    for (int i = 0; i < 10000000; i++) {
        pthread_mutex_lock(&lock);     // one thread at a time
        bill = bill + 1;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main() {
    pthread_t a, b;
    pthread_create(&a, NULL, add_orders, NULL);
    pthread_create(&b, NULL, add_orders, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("expected 20000000, got %d\n", bill);
    return 0;
}

Output:

expected 20000000, got 20000000

A mutex (mutual exclusion lock) lets only one thread at a time hold it. pthread_mutex_lock waits until the lock is free and takes it; pthread_mutex_unlock releases it. Other ways to be thread-safe: atomic operations (one indivisible read-add-write, see practice 3), giving each thread its own data (practice 1), or immutable data that nobody changes. Locks, their costs and traps (deadlock) get episodes 24 to 29.

Problem 6: a function with a memory (reentrant functions)

#include <stdio.h>
#include <string.h>

int main() {
    char orders[] = "chai,samosa;coffee,vada";   // two tables
    char *table = strtok(orders, ";");
    while (table) {
        printf("table: ");
        char *item = strtok(table, ",");        // nested strtok!
        while (item) {
            printf("%s ", item);
            item = strtok(NULL, ",");
        }
        printf("\n");
        table = strtok(NULL, ";");
    }
    return 0;
}

Output:

table: chai samosa 

The second table vanished. strtok splits a string into tokens (pieces between separators). It remembers where it stopped in a hidden static variable, one copy for the whole program. The inner loop's calls overwrote the outer loop's place, so the outer loop's next call found nothing left.

A function is reentrant if it can safely be called again before an earlier call has finished: from a nested loop, from a signal handler that interrupts it, or from another thread. The rule: no hidden static or global state; use only arguments and local variables (or state the caller passes in).

#include <stdio.h>
#include <string.h>

int main() {
    char orders[] = "chai,samosa;coffee,vada";
    char *s1, *s2;                              // each loop keeps its OWN place
    char *table = strtok_r(orders, ";", &s1);
    while (table) {
        printf("table: ");
        char *item = strtok_r(table, ",", &s2);
        while (item) {
            printf("%s ", item);
            item = strtok_r(NULL, ",", &s2);
        }
        printf("\n");
        table = strtok_r(NULL, ";", &s1);
    }
    return 0;
}

Output:

table: chai samosa 
table: coffee vada 

strtok_r is the reentrant version: you pass in your own save pointer (place-keeper). Other _r functions follow the same idea (localtime_r, rand_r).

Reentrant vs thread-safe

Reentrant Thread-safe
Means Safe to re-enter before the previous call finished Safe when called by many threads at once
How No shared state at all No shared state, or shared state protected by a lock
Relation A reentrant function is (normally) also thread-safe A thread-safe function with a lock is not reentrant: if a signal handler interrupts it while it holds the lock and calls it again, it waits for itself forever

The whole chain

Step Fix Its limit (the next problem)
One worker: 4.0 s — Every wait blocks the rest
Four processes Waits overlap Copies, IPC, costly switches
Threads: 1.0 s Many flows, one memory Who schedules them?
User vs kernel threads, models Many-to-one, one-to-one, many-to-many One thread per task is costly
Thread pools, virtual threads Reuse workers / cheap threads Shared data gets corrupted
Mutex Thread safety Hidden state inside functions
Reentrant functions No hidden shared state —

Common mistakes (and the real output)

Mistake Real output Why Fix
job.run() instead of new Thread(job).start() main is cooking run() is a normal method call start()
Two threads doing bill = bill + 1 with no lock expected 20000000, got 10166098 read-add-write steps interleave mutex or atomic
strtok inside a strtok loop table: chai samosa (second table lost) strtok's position is a hidden static strtok_r
main returns without pthread_join main: done only; dish ready never prints returning from main ends the process and all its threads pthread_join every thread
Passing &d (the loop variable) to every thread threads may all see the same or a later value they share one variable that keeps changing pass the value, or a separate slot per thread (id[d])
Thinking volatile makes code thread-safe still loses updates volatile only stops the compiler caching the value locks or atomics

The pthread_join case, run for real:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *cook(void *arg) {
    sleep(1);
    printf("dish ready\n");
    return NULL;
}

int main() {
    pthread_t t;
    pthread_create(&t, NULL, cook, NULL);
    printf("main: done\n");
    return 0;                       // no pthread_join!
}

Output: main: done (nothing else).

Mini project: split a big sum across threads

Each thread sums one quarter of 1..1,000,000 into its own slot of an array, so no two threads write the same memory and no lock is needed. The main thread joins them and adds the four parts.

#include <stdio.h>
#include <pthread.h>

long long part[4];                  // one slot per thread: no sharing conflicts

void *sum_quarter(void *arg) {
    long q = (long)arg;
    long from = q * 250000 + 1, to = (q + 1) * 250000;
    long long s = 0;
    for (long i = from; i <= to; i++) s += i;
    part[q] = s;
    return NULL;
}

int main() {
    pthread_t t[4];
    for (long q = 0; q < 4; q++) pthread_create(&t[q], NULL, sum_quarter, (void *)q);
    long long total = 0;
    for (int q = 0; q < 4; q++) { pthread_join(t[q], NULL); total += part[q]; }
    printf("sum = %lld (formula: %lld)\n", total, 1000000LL * 1000001 / 2);
    return 0;
}

Output:

sum = 500000500000 (formula: 500000500000)

Extension: time it with 1, 2 and 4 threads and a bigger range; on a 2-core machine, more than 2 threads won't make heavy maths faster.

Practice

1. Sum 1..1,000,000 with 4 threads, each a quarter.

Solution

The mini project above. Key idea: give each thread its own output slot, then combine after pthread_join.

2. Make the race lose more or fewer updates: try 2, 4 and 8 threads.

Solution
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

volatile int bill = 0;

void *add(void *arg) {
    for (int i = 0; i < 1000000; i++) bill = bill + 1;
    return NULL;
}

int main(int argc, char **argv) {
    int n = argc > 1 ? atoi(argv[1]) : 2;
    pthread_t t[16];
    for (int i = 0; i < n; i++) pthread_create(&t[i], NULL, add, NULL);
    for (int i = 0; i < n; i++) pthread_join(t[i], NULL);
    printf("%d threads: expected %d, got %d\n", n, n * 1000000, bill);
    return 0;
}

One run each (./a.out 2, 4, 8) on a 2-core machine:

2 threads: expected 2000000, got 1053456
4 threads: expected 4000000, got 2852712
8 threads: expected 8000000, got 4860914

Every run gives different numbers; with a single core the loss is usually much smaller, because threads interleave only at timer interrupts.

3. Fix the race without a mutex.

Solution

Use an atomic add: one indivisible read-add-write.

#include <stdio.h>
#include <pthread.h>
#include <stdatomic.h>

atomic_int bill = 0;

void *add_orders(void *arg) {
    for (int i = 0; i < 10000000; i++)
        atomic_fetch_add(&bill, 1);     // read-add-write as ONE step
    return NULL;
}

int main() {
    pthread_t a, b;
    pthread_create(&a, NULL, add_orders, NULL);
    pthread_create(&b, NULL, add_orders, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("expected 20000000, got %d\n", bill);
    return 0;
}

Output: expected 20000000, got 20000000. In Java, use AtomicInteger.incrementAndGet().

4. Java: run 10 tasks on a pool of 3 threads and print which threads were used.

Solution
import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Future<String>> results = new ArrayList<>();
        for (int task = 1; task <= 10; task++) {
            int id = task;
            results.add(pool.submit(() -> "task " + id + " on " + Thread.currentThread().getName()));
        }
        Set<String> names = new TreeSet<>();
        for (Future<String> f : results) {
            String r = f.get();             // waits for that task's result
            names.add(r.substring(r.indexOf("pool")));
        }
        pool.shutdown();
        System.out.println("threads used: " + names);
    }
}

One run:

threads used: [pool-1-thread-1, pool-1-thread-2, pool-1-thread-3]

A Future is a handle to a result that will be ready later; get() waits for it. Ten tasks, at most three threads.

5. Is this function reentrant? Thread-safe? int next_ticket() { static int n = 0; return ++n; }

Solution

Neither. static int n is hidden shared state: two threads can both read the same n and hand out the same ticket (a race), and a nested call from a signal handler can interrupt between the read and the write. Make it thread-safe with a lock or atomic_fetch_add; make it reentrant by letting the caller own the counter: int next_ticket(int *n) { return ++*n; }.

6. A process has 3 threads. How many stacks, program counters and heaps does it have?

Solution

3 stacks, 3 program counters (and 3 register sets), 1 heap (shared), 1 code section, 1 set of open files.

7. In the many-to-one model, one thread calls read() on a slow network socket. What happens to the other threads?

Solution

They all stop. The kernel sees only one kernel thread; when it blocks in read, the whole process blocks. In one-to-one or many-to-many, only the calling thread blocks.

Quick quiz

int total = 0;               // A
int *buf = malloc(100);      // B
FILE *f = fopen("menu", "r"); // C
void *work(void *a) {
    int count = 0;           // D
}

Which is not shared by the threads of a process? A. the global total B. the heap memory buf points to C. the open file f D. the local count

Answer

D. Locals live on each thread's own stack. Globals, the heap and open files are shared.

Interview questions

  1. Process vs thread? A process is a running program with its own memory; a thread is a flow of execution inside a process. Threads of a process share memory and files; each has its own stack, PC and registers.
  2. What do threads share and not share? Shared: code, globals, heap, open files. Private: stack, PC, registers, thread id, thread-local storage.
  3. What is a TCB? The kernel's per-thread record: id, state, saved PC and registers, stack pointer, priority, pointer to the PCB.
  4. Why are threads cheaper than processes? No new address space to create or switch; they share the process's resources.
  5. User-level vs kernel-level threads? User threads are managed by a library (fast, but a blocking call blocks all, one core); kernel threads are managed by the OS (slower to switch, block independently, use many cores).
  6. Explain many-to-one, one-to-one, many-to-many. How user threads map to kernel threads; trade-offs above. Linux pthreads is one-to-one.
  7. Concurrency vs parallelism? Taking turns over a period vs running at the same instant on several cores.
  8. Multithreading vs multiprocessing? Shared memory and cheap but a crash kills all; separate memory and isolated but heavier and needs IPC.
  9. start() vs run() in Java? start() creates a new thread that calls run(); calling run() directly runs on the current thread.
  10. What is a thread pool and why use it? Reusable worker threads that take tasks from a queue; avoids creation cost and too many threads.
  11. What is a race condition? How do you prevent it? A result that depends on thread timing; use locks, atomics, or no shared mutable data.
  12. Thread-safe vs reentrant? Reentrant: safe to re-enter before finishing (no shared state). Thread-safe: correct under concurrent calls (may use locks). A locked function is thread-safe but not reentrant.
  13. What is a green thread? A thread scheduled by a runtime instead of the OS (user-level).
  14. What happens if main returns while threads are running (C)? The process ends and all threads with it; join them first (or call pthread_exit in main).

Glossary

Term Meaning in plain words Example
Thread A single flow of execution inside a process a cook in the kitchen
Main thread The thread every process starts with runs main
Lightweight process Another name for a thread —
Program counter (PC) Address of the next instruction a thread will run private per thread
Registers Small fast storage in the CPU a thread computes with private per thread
Stack Memory for a thread's local variables and function calls int mine
Heap Memory from malloc / new, shared by all threads malloc(100)
Address space The memory a process can see one per process
Thread control block (TCB) Kernel record of a thread: id, state, saved PC/registers, SP, priority saved on a thread switch
Process control block (PCB) Kernel record of a process (episode 17) one per process
pthreads POSIX threads library pthread_create
pthread_create Start a new thread running a function pthread_create(&t, NULL, cook, arg)
pthread_join Wait for a thread to finish pthread_join(t, NULL)
pthread_t Type that holds a thread id pthread_t t;
void * A pointer to anything thread argument
Responsiveness / economy / scalability Benefits of threads see table
Concurrency Tasks progressing over the same period by taking turns one cook, four pans
Parallelism Tasks running at the same instant on several cores four cooks
Multithreading Many threads in one process a game engine
Multiprocessing Many processes (or a machine with many CPUs) browser tabs
User-level thread Thread managed by a library, invisible to the kernel green threads
Kernel-level thread Thread created and scheduled by the OS Linux pthreads
Green thread Thread scheduled by a runtime/VM instead of the OS classic user threads
Blocking system call A call where the kernel makes the caller wait read on a socket
Many-to-one model Many user threads on one kernel thread green threads
One-to-one model Each user thread has its own kernel thread NPTL
Many-to-many model N user threads on M kernel threads Java virtual threads
Two-level model Many-to-many plus optional bound threads —
NPTL Native POSIX Threads Library, glibc's 1:1 pthreads Linux
Runnable A Java job with a run() method () -> {...}
Lambda Short syntax for a function object () -> System.out.println("hi")
Thread.start() / run() Start a new thread / just call the method t1.start()
join() Wait for a thread to finish t1.join()
Thread pool Reusable worker threads taking tasks from a queue newFixedThreadPool(2)
Task queue Where tasks wait for a free worker the pool's queue
ExecutorService Java interface for running tasks on threads pool.submit(...)
Future Handle to a result that will be ready later f.get()
Virtual thread Cheap JVM-managed thread on top of platform threads (Java 21) newVirtualThreadPerTaskExecutor()
Platform thread A Java thread backed one-to-one by an OS thread new Thread(...)
volatile (C) Tell the compiler to really access memory each time; not a lock volatile int bill
Lost update One thread's write overwrites another's bill +1 instead of +2
Race condition Result depends on thread timing the bill demo
Critical section Code touching shared data that must not run in two threads at once bill = bill + 1
Thread-safe Correct even with many threads at once the mutex version
Mutex Mutual exclusion lock: one holder at a time pthread_mutex_lock
Atomic operation An operation that happens as one indivisible step atomic_fetch_add
Token A piece of a string between separators "chai"
Static variable A variable that keeps its value between calls, one copy strtok's position
Reentrant function Safe to call again before an earlier call finishes strtok_r
Save pointer Caller-owned place-keeper passed to strtok_r &s1
Thread-local storage A variable with a separate copy per thread __thread int x;

Summary

  • A thread is a flow of execution inside a process. Threads share code, globals, heap and open files; each keeps its own PC, registers and stack, recorded in a TCB.
  • Threads overlapped four 1-second waits into 1.0 s, and returned results through a plain global array: cheaper and simpler than processes + IPC.
  • Concurrency = taking turns over a period; parallelism = at the same instant on several cores.
  • User-level threads are fast but block together and use one core; kernel-level threads block independently and use many cores. Models: many-to-one, one-to-one (Linux NPTL), many-to-many (Java 21 virtual threads).
  • Java: start() makes a thread, run() doesn't; thread pools reuse workers; virtual threads make waiting cheap.
  • Sharing causes race conditions (lost updates); a mutex or atomic makes code thread-safe.
  • Reentrant functions keep no hidden state (strtok_r, not strtok).

Next episode: CPU scheduling 1: preemptive vs non-preemptive, scheduling criteria, turnaround and waiting time, Gantt charts and FCFS numericals.

Sources: Linux pthreads(7) manual (manpages.karlosoft.com) for NPTL being 1:1; InfoQ, "Java 21 released", 19 Sep 2023 for JEP 444 finalizing virtual threads in JDK 21; Azul, "JDK 21 delivers virtual threads" for platform threads mapping one-to-one to OS threads and many virtual threads sharing a platform thread. Every program above was run on 30 October 2026.