linux-sysprog · beginner · ~15 min

Is the operation atomic?

Tell race-safe operations from racy ones.

Challenge

A plain x++ is three steps (load, add, store) that can interleave across threads; atomics and mutexes make it indivisible. Classify an operation as race-safe or not.

Task

Implement int op_is_safe(const char *op) that returns 1 if op names a race-safe operation, else 0.

Input

  • op: an operation name string.

Output

1 for "atomic_fetch_add" or "mutex_guarded"; 0 for "plain_plusplus".

Example

op_is_safe("atomic_fetch_add")   ->   1
op_is_safe("mutex_guarded")      ->   1
op_is_safe("plain_plusplus")     ->   0

Input format

op: an operation name string.

Output format

1 for atomic_fetch_add/mutex_guarded, else 0.

Constraints

plain_plusplus is racy; the others are safe.

Starter code

#include <string.h>

int op_is_safe(const char *op) {
    /* TODO */
    return 0;
}

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