linux-sysprog · beginner · ~15 min

Useful thread count

Cap parallelism at the lesser of cores and tasks.

Challenge

Spawning more threads than you have cores or tasks just wastes resources, so the useful count is the smaller of the two. Compute it.

Task

Implement int useful_threads(int cores, int tasks) that returns the number of threads worth spawning.

Input

  • cores: number of CPU cores.
  • tasks: number of independent tasks.

Output

min(cores, tasks), or 0 if either is <= 0.

Example

useful_threads(4, 10)   ->   4
useful_threads(8, 3)    ->   3
useful_threads(0, 5)    ->   0

Edge cases

  • Either argument <= 0: return 0.

Input format

cores: CPU cores; tasks: independent tasks.

Output format

min(cores, tasks), or 0 if either is <= 0.

Constraints

Non-positive input yields 0.

Starter code

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.