linux-sysprog · beginner · ~15 min
Decide when synchronisation is actually required.
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.
Implement int needs_sync(int shared, int written_by_multiple) that returns 1 only when both conditions hold.
shared: 1 if the data is shared between threads, else 0.written_by_multiple: 1 if more than one thread writes it, else 0.1 if shared AND written_by_multiple; else 0.
needs_sync(1, 1) -> 1
needs_sync(1, 0) -> 0 (read-only)
needs_sync(0, 1) -> 0 (thread-local)
shared: 1 if shared; written_by_multiple: 1 if multiple writers.
1 if both flags are set, else 0.
Both conditions must hold.
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.