linux-sysprog · beginner · ~10 min

Spawn N threads, join all

Two parallel loops: spawn then join. Track all thread IDs.

Challenge

Spawn a pool of n threads and join them all — the spawn-loop / join-loop pattern that every multithreaded program uses.

Task

Implement int run_n_threads(int n) that creates n threads and waits for all of them.

Input

  • n: how many threads to spawn. Each thread's worker does nothing and returns immediately.

Output

Stores all n thread IDs, joins them, and returns n on success. Returns -1 if any pthread_create or pthread_join fails.

Example

run_n_threads(0)    ->   0
run_n_threads(1)    ->   1
run_n_threads(4)    ->   4
run_n_threads(16)   ->   16

Edge cases

  • n == 0: nothing to spawn, returns 0.
  • Any create/join failure returns -1.

Rules

  • Keep every thread ID so you can join each one (don't lose handles).

Why this matters

Real programs spawn a pool of threads, not one. Practice the spawn-loop + join-loop pattern.

Input format

n: the number of no-op threads to spawn.

Output format

n on success (all threads created and joined), or -1 on any create/join failure.

Constraints

Store all n thread IDs; spawn in one loop, join in another. n == 0 returns 0.

Starter code

#include <pthread.h>
int run_n_threads(int n) {
    /* TODO */
    return -1;
}

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.