Chapter 4: Threads

Operating Systems · Study Questions
Basic conceptsConcurrency and parallelismAmdahl’s lawMapping modelsPthreads and JavaImplicit threadingThreading issuesRace conditions
Sercan KÜLCÜ

Multiple Choice · Basic Concepts

Question 1: Which One Is Not Shared?

Consider two threads in the same process. Which of the following is NOT shared between them, i.e. is private to each?

C: The address space (code, data, heap) and resources such as open files and signal handlers belong to the process and are shared by all its threads. Each thread has its own execution state: program counter, registers and stack. The stack is private but not protected: a bad pointer can corrupt another thread’s stack.

Classic Question · Basic Concepts

Question 2: A Multithreaded Web Server

In a web server, 2/3 of the requests are served from the cache and take 15 ms of CPU. The other 1/3 also need a disk read: 15 ms of CPU plus a 75 ms disk wait. There is one CPU; the disk can serve many requests at once. How many requests per second does the server answer if it is single-threaded, and if it is multithreaded?

Show answer
  • Single thread: while the disk is awaited the process blocks and the CPU sits idle. The average request time is 2/3 × 15 + 1/3 × 90 = 10 + 30 = 40 ms → 25 requests/s.
  • Multiple threads: while one worker blocks on the disk, another uses the CPU; the disk waits overlap. Each request spends only 15 ms of CPU → 1000 / 15 ≈ 66.7 requests/s.

The gain comes not from parallelism (there is one CPU) but from overlapping blocking calls with computation; the code stays sequential and readable. The same overlap is possible with a single-threaded event-driven design, but the code becomes more complex.

Step-by-Step Trace · Multicore Programming

Question 3: Amdahl’s Law

20% of a program’s running time cannot be parallelized. What are the speedup and efficiency on 2, 4 and 8 cores? What is the upper bound as the number of cores goes to infinity?

single coreserialparallel 0.8N = 1time 1 → 1×

On a single core the time is 100%: 20% serial + 80% parallel.

single coreserialparallel 0.8N = 2time 0.6 → 1.67×

0.2 + 0.8 / 2 = 0.6 → 1 / 0.6 ≈ 1.67×: the cores doubled but the speedup is not 2.

single coreserialparallel 0.8N = 4time 0.4 → 2.5×

0.2 + 0.2 = 0.4 → 2.5×. The serial part is now half of the time.

single coreserialparallel 0.8N = 8time 0.3 → 3.33×

0.2 + 0.1 = 0.3 → 3.33×; the efficiency of 8 cores is 42%. Going from 4 to 8 cores gained only a factor of 1.33.

single coreserialparallel 0.8N → ∞time 0.2 → 5×

The parallel term goes to zero and the serial 0.2 remains: at most 5×. A seemingly small serial part limits scaling.

S = 0.2 (serial), 1 − S = 0.8 (parallel)
time(N) = S + (1 − S) / N
speedup(N) = 1 / time(N)
efficiency(N) = speedup(N) / N
upper bound (N → ∞) = 1 / S

Multiple Choice · Multicore Programming

Question 4: Four Threads on One Core

On a single-core machine four threads run in turn by time sharing. Which statement is true for this situation?

B: All four make progress during the same time interval (concurrency), but only one runs at any instant. Parallelism needs at least two cores. Parallelism implies concurrency but not the reverse, so A is impossible.

Classic Question · Multicore Programming

Question 5: Serial Fraction for a Target Speedup

On a 16-core server a computation must run at least 8 times faster. By Amdahl’s law, what is the largest percentage the serial (non-parallelizable) part can have? What would the speedup on 16 cores be if the serial part were 10%?

Show answer

8 = 1 / (S + (1 − S) / 16) ⇒ S + (1 − S) / 16 = 1/8 ⇒ 16S + 1 − S = 2 ⇒ 15S = 1 ⇒ S = 1/15 ≈ 6.7%.

So at least 93.3% of the code must be parallel. Check: 1 / (0.0667 + 0.9333 / 16) = 1 / 0.125 = 8.

With S = 10%: 1 / (0.1 + 0.9 / 16) = 1 / 0.15625 = 6.4× (efficiency 40%). Even a 10% serial part sharply reduces scaling: only 40% of the 16 cores are used efficiently; in practice synchronization and communication overhead reduce the speedup further.

Multiple Choice · Threading Models

Question 6: read() in the Many-to-One Model

In the many-to-one (N:1) model, one of a process’s 8 user-level threads makes a blocking read() system call. What happens?

A: The kernel sees a single schedulable entity (one kernel thread) in this process; when it blocks, the library cannot switch to another thread. For the same reason the N:1 model cannot use multiple cores. B is the behavior of the 1:1 model.

Classic Question · Threading Models

Question 7: Switch Cost and Blocking

A program performs 1,000,000 thread switches. A user-level (N:1) switch takes 40 ns, a kernel-level (1:1) switch takes 1.6 µs. How much total time do the switches cost? What happens in the two models when one thread performs an 8 ms disk read?

Show answer
  • N:1: 10⁶ × 40 ns = 0.04 s; 1:1: 10⁶ × 1.6 µs = 1.6 s → 40 times. A user-level switch involves no trap; the kernel is not entered.
  • On the disk read, in the N:1 model the whole process waits 8 ms: the kernel sees a single kernel thread and blocks it.
  • In the 1:1 model only the reading thread waits; the others run during those 8 ms (even in parallel on other cores).

The M:N model (Go, Java virtual threads) tries to combine the strengths of both: cheap switches and a runtime that does not block.

Multiple Choice · Threading Models

Question 8: Java Virtual Threads

Which statement about Java 21’s virtual threads (Thread.ofVirtual()) is true?

D: The JVM multiplexes many virtual threads onto a few platform (carrier) threads. On blocking I/O the virtual thread is unmounted from its carrier, and the carrier runs another virtual thread. The kernel sees only the carriers; that is why millions of virtual threads are possible.

Step-by-Step Trace · Thread Libraries

Question 9: A Sum with Three Threads

What does the program print? Does the result depend on the order in which the threads run? What would happen if the second loop (join) were deleted?

mainrunningT0noneT1noneT2nonepartial:[0]0[1]0[2]0

The process starts with a single thread (main); the global partial is zero.

mainrunningT0readyT1readyT2readypartial:[0]0[1]0[2]0

Three threads are created; each gets its own id[k] address. The scheduler decides which one runs first.

mainwaitingT0readyT1runningT2readypartial:[0]0[1]0[2]0

main blocks in pthread_join(t[0]). In this run T1 was picked first.

mainwaitingT0runningT1doneT2readypartial:[0]0[1]26[2]0

T1: 5 + 6 + 7 + 8 = 26. Each thread writes only to its own cell: no race.

mainwaitingT0doneT1doneT2runningpartial:[0]10[1]26[2]0

T0: 1 + 2 + 3 + 4 = 10.

mainwaitingT0doneT1doneT2donepartial:[0]10[1]26[2]42

T2: 9 + 10 + 11 + 12 = 42.

mainrunningT0doneT1doneT2donepartial:[0]10[1]26[2]42total = 78

All three joins return; total = 10 + 26 + 42 = 78. Whatever the run order, the joins guarantee that all threads have finished.

mainrunningT0doneT1doneT2donepartial:[0]10[1]26[2]42total = 78

The output is the same in every run. Without the joins, main could read partial sums, and returning from main would terminate the whole process together with the threads.

int partial[3];
void *worker(void *arg) {
  int k = *(int *)arg;
  for (int i = 4*k + 1; i <= 4*k + 4; i++)
    partial[k] += i;
  return NULL;
}
int main(void) {
  pthread_t t[3]; int id[3] = {0, 1, 2};
  for (int k = 0; k < 3; k++)
    pthread_create(&t[k], NULL, worker, &id[k]);
  int total = 0;
  for (int k = 0; k < 3; k++) {
    pthread_join(t[k], NULL);
    total += partial[k];
  }
  printf("%d %d %d -> %d\n",
         partial[0], partial[1], partial[2], total);
}

Multiple Choice · Thread Libraries

Question 10: The Address of the Loop Variable

The programmer expects to see 0 1 2 on the screen. Which statement is true?

void *print_id(void *arg) {
  printf("%d ", *(int *)arg);
  return NULL;
}
int main(void) {
  pthread_t t[3];
  for (int i = 0; i < 3; i++)
    pthread_create(&t[i], NULL, print_id, &i);
  for (int j = 0; j < 3; j++)
    pthread_join(t[j], NULL);
  return 0;
}

C: All three threads receive the address of the same variable i; i may have changed by the time they read it: outputs such as 1 1 3 or 2 3 3 are possible. Also, i’s lifetime ends after the loop, so reading it is undefined behavior. Fix: separate storage for each thread (int id[3], &id[i]).

Output Question · Thread Libraries

Question 11: run() or start()?

The thread’s name is "worker". What does the program print? Why does t.run() not start a new thread?

public class Name {
  public static void main(String[] a)
      throws Exception {
    Thread t = new Thread(() ->
      System.out.println("1: " +
        Thread.currentThread().getName()),
      "worker");
    t.run();
    t.start();
    t.join();
    System.out.println("2: " +
      Thread.currentThread().getName());
  }
}
Show answer
1: main
1: worker
2: main
  • t.run() is an ordinary method call: the lambda runs inside the caller, i.e. the main thread → “1: main”.
  • t.start() starts a new operating-system thread; the lambda runs there → “1: worker”.
  • Because join waits for it to finish, the order is deterministic; main prints the last line.

A Thread object can be started only once; a second start throws IllegalThreadStateException.

Step-by-Step Trace · Implicit Threading

Question 12: A Sum with Fork-Join

With THRESHOLD = 2, what value does invoke return? Draw the task tree; write the result of each node.

[0,8) ?

The root task has 8 elements: 8 − 0 > THRESHOLD → it is split.

[0,8) ?[0,4) ?[4,8) ?

left.fork(): [0,4) goes to the pool’s queue; an idle worker may steal it. The same thread computes [4,8) itself.

[0,8) ?[0,4) ?[4,8) ?[4,6) ?[6,8) = 9

[4,8) is split too: [4,6) is forked, [6,8) is computed directly: 1 + 8 = 9.

[0,8) ?[0,4) ?[4,8) = 19[4,6) = 10[6,8) = 9

left.join(): [4,6) = 2 + 8 = 10 → [4,8) = 10 + 9 = 19.

[0,8) ?[0,4) = 18[4,8) = 19[0,2) = 9[2,4) = 9[4,6) = 10[6,8) = 9

[0,4) the same way: [0,2) = 2 + 7 = 9, [2,4) = 1 + 8 = 9 → 18. This branch most likely ran on another worker (work stealing).

[0,8) = 37[0,4) = 18[4,8) = 19[0,2) = 9[2,4) = 9[4,6) = 10[6,8) = 9

Root: 18 + 19 = 37. 7 tasks, 4 leaves. Which worker ran which task may vary; the result does not.

class SumTask extends RecursiveTask<Integer> {
  static final int THRESHOLD = 2; // + a, lo, hi, constructor
  protected Integer compute() {
    if (hi - lo <= THRESHOLD) {
      int s = 0;
      for (int i = lo; i < hi; i++) s += a[i];
      return s;
    }
    int mid = (lo + hi) / 2;
    SumTask left = new SumTask(a, lo, mid);
    SumTask right = new SumTask(a, mid, hi);
    left.fork();
    int rightResult = right.compute();
    return left.join() + rightResult;
  }
}
// a = {2, 7, 1, 8, 2, 8, 1, 8}
SumTask t = new SumTask(a, 0, 8);
ForkJoinPool.commonPool().invoke(t);

Multiple Choice · Implicit Threading

Question 13: An OpenMP Parallel Region

The program is compiled with -fopenmp and run. Which statement about the output is true?

#include <omp.h>
#include <stdio.h>
int main(void) {
  #pragma omp parallel num_threads(3)
  printf("hello\n");
  printf("done\n");
  return 0;
}

B: #pragma omp parallel applies only to the single statement that follows: a team of 3 threads is created and each prints “hello” (order undefined). There is an implicit barrier at the end of the region; then only the master thread prints “done”. num_threads(3) overrides the default thread count (the number of cores).

Classic Question · Implicit Threading

Question 14: How Big Should the Pool Be?

On an 8-core machine two pools are set up: one for image-compression tasks that only compute, the other for tasks that on each request compute for 5 ms and then wait 45 ms for a database reply. How would you choose the pool sizes?

Show answer
  • CPU-bound: about the number of cores, 8 (or 9). More adds no parallelism, only context switches and cache contention.
  • I/O-bound: rule of thumb Nthreads ≈ Ncores × (1 + wait / compute) = 8 × (1 + 45 / 5) = 80. While one thread waits, the other 9 can use that core.

A pool limits the number of concurrent threads and pays the creation cost once; the size should be tuned by measurement: a pool that is too large consumes memory, one that is too small leaves the CPU idle.

Multiple Choice · Threading Issues

Question 15: fork() in a Multithreaded Process

A thread in a process with 8 threads calls fork() (POSIX/Linux). Which statement about the child process is true?

D: The whole address space is copied, but only one of the threads. A mutex held by another thread (e.g. inside malloc) may stay locked forever in the child. That is why exec right after fork is recommended; often posix_spawn is a better choice.

Classic Question · Threading Issues

Question 16: Lost Increments

The shared counter is 0. T1 and T2 each execute counter++ twice; each increment has two steps: read (r = counter) and write (counter = r + 1). If the steps run in this order, what is the final value: T1.read, T1.write, T2.read, T1.read, T2.write, T1.write, T2.read, T2.write? What final values are possible over all interleavings?

Show answer
stepT1.readT1.writeT2.readT1.readT2.writeT1.writeT2.readT2.write
rr1 = 0r2 = 1r1 = 1r2 = 2
counter01112223

The final value is 3: T1 and T2 read the same value 1 and both wrote 2, so one increment was lost. Over all 70 possible interleavings the result is 2, 3 or 4; it is at least 2 because the last write of each thread depends on a read after its own first write. 4 is guaranteed only if the increment is made atomic (mutex, atomic_fetch_add).

Multiple Choice · Threading Issues

Question 17: A Separate Copy per Thread

A variable is needed that holds each thread’s own error code but can be accessed from all functions like a global (like errno in C). Which one is used?

A: A TLS variable exists as a separate copy in each thread and lives as long as the thread. Global and heap variables are shared; a local variable disappears when the function returns and other functions cannot reach it. In today’s C libraries errno is already thread-local.

The End

Chapter 4: Threads: Study Questions
Lecture slides: Chapter 4: Threads · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.