Lock-Free Synchronization with Shared Flags

Infrastructure, Parallelism & Hardware Efficiency DS practice problem on Onlearn.

Difficulty: medium.

Topics: Lock-Free Synchronization with Shared Flags, Compare-And-Swap (CAS), Memory Barriers, Volatile Variables, Spinlocks, False Sharing, Parallel Computing, Distributed Systems, Computer Architecture, Operating Systems, High-Performance Computing, Concurrent Data Structures, Memory Consistency Models, Atomic Operations, Inter-Process Communication, Hardware Cache Coherency.

Implement a simulator for lock free coordination between multiple workers using a shared flag array. This pattern is fundamental in systems programming where threads or processes synchronize without using locks or mutexes, instead relying on shared memory flags to signal state changes. You are given N workers that execute operations sequentially from their own operation lists. All workers share a single integer flag array (initialized to zeros) that they use to coordinate. Each worker's operation list contains operations of three types: ("set", flag index, value) write value into flags[flag index] ("wait", flag index, value) block until flags[flag index] equals value ("work", worker id, task id) record a completed task as the tuple (worker id, task id) The simulator runs in rounds. Each round iterates through workers 0 to N 1 in order and attempts to execute each worker's next pending operation: A set operation always executes immediately. A wait operation executes (advances) only if the flag condition is currently satisfied; otherwise the worker is skipped for this round. A work operation always executes immediately. Each worker executes at most one operation per round. If a full round completes with no worker making any progress, the system is in deadlock. The simulation also halts after max rounds rounds. Write a function simulate lock free sync that returns a dictionary with three keys: "completed": a list of (worker id, task id) tuples in the order tasks were completed "flags": the final state of the flag array as a list of integers "deadlock": a boolean indicating whether deadlock was detected