linux-sysprog · beginner · ~15 min
Cap parallelism at the lesser of cores and tasks.
Spawning more threads than you have cores or tasks just wastes resources, so the useful count is the smaller of the two. Compute it.
Implement int useful_threads(int cores, int tasks) that returns the number of threads worth spawning.
cores: number of CPU cores.tasks: number of independent tasks.min(cores, tasks), or 0 if either is <= 0.
useful_threads(4, 10) -> 4
useful_threads(8, 3) -> 3
useful_threads(0, 5) -> 0
<= 0: return 0.cores: CPU cores; tasks: independent tasks.
min(cores, tasks), or 0 if either is <= 0.
Non-positive input yields 0.
int useful_threads(int cores, int tasks) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.