linux-sysprog · beginner · ~15 min

Detached vs joinable

Account for thread cleanup.

Challenge

A joinable thread that is never joined leaks its stack and control block until the process exits; a detached thread cleans up on its own. Count the leaks.

Task

Implement int leaked_threads(int created, int joined, int detached) that returns how many joinable threads were never joined.

Input

  • created: total threads created.
  • joined: how many were joined.
  • detached: how many were detached.

Output

created - joined - detached, floored at 0.

Example

leaked_threads(10, 6, 2)   ->   2
leaked_threads(5, 5, 0)    ->   0
leaked_threads(4, 0, 4)    ->   0   (all detached)

Edge cases

  • All threads joined or detached: return 0.

Input format

created: threads made; joined: joined count; detached: detached count.

Output format

created - joined - detached, floored at 0.

Constraints

Result is never negative.

Starter code

int leaked_threads(int created, int joined, int detached) {
    /* TODO */
    return 0;
}

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