linux-sysprog · beginner · ~10 min
Two parallel loops: spawn then join. Track all thread IDs.
Spawn a pool of n threads and join them all — the spawn-loop / join-loop pattern that every multithreaded program uses.
Implement int run_n_threads(int n) that creates n threads and waits for all of them.
n: how many threads to spawn. Each thread's worker does nothing and returns immediately.Stores all n thread IDs, joins them, and returns n on success. Returns -1 if any pthread_create or pthread_join fails.
run_n_threads(0) -> 0
run_n_threads(1) -> 1
run_n_threads(4) -> 4
run_n_threads(16) -> 16
n == 0: nothing to spawn, returns 0.-1.Real programs spawn a pool of threads, not one. Practice the spawn-loop + join-loop pattern.
n: the number of no-op threads to spawn.
n on success (all threads created and joined), or -1 on any create/join failure.
Store all n thread IDs; spawn in one loop, join in another. n == 0 returns 0.
#include <pthread.h>
int run_n_threads(int n) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.