linux-sysprog · beginner · ~15 min

Does this need synchronisation?

Decide when synchronisation is actually required.

Challenge

Data needs a lock only when it is both shared between threads and written by more than one of them. Immutable shared data and thread-local data are race-free without locks. Decide whether synchronisation is required.

Task

Implement int needs_sync(int shared, int written_by_multiple) that returns 1 only when both conditions hold.

Input

  • shared: 1 if the data is shared between threads, else 0.
  • written_by_multiple: 1 if more than one thread writes it, else 0.

Output

1 if shared AND written_by_multiple; else 0.

Example

needs_sync(1, 1)   ->   1
needs_sync(1, 0)   ->   0   (read-only)
needs_sync(0, 1)   ->   0   (thread-local)

Input format

shared: 1 if shared; written_by_multiple: 1 if multiple writers.

Output format

1 if both flags are set, else 0.

Constraints

Both conditions must hold.

Starter code

int needs_sync(int shared, int written_by_multiple) {
    /* TODO */
    return 0;
}

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