TASK
Implementation
Implement your counter using Compare-And-Swap (CAS) operations. CAS atomically updates a value only if it matches an expected value, preventing lost updates.
Sample Test Cases
CAS-based counterTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"add","msg_id":2,"delta":5}}
{"src":"c2","dest":"n1","body":{"type":"read","msg_id":3}}
Expected Output
{"src":"n1","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}
{"src":"n1","dest":"c1","body":{"type":"add_ok","in_reply_to":2,"msg_id":1}}
{"src":"n1","dest":"c2","body":{"type":"read_ok","in_reply_to":3,"msg_id":2,"value":5}}
Hints
Hint 1▾
Read current value, compute new, CAS to update
Hint 2▾
Retry on CAS failure
Hint 3▾
Handle the race between read and CAS
OVERVIEW
Theoretical Hub
Compare-And-Swap
CAS is the foundation of lock-free algorithms. It atomically checks if a value equals an expected value and, if so, updates it. If the check fails, someone else modified the value and you must retry.
Key Concepts
CASoptimistic concurrencyatomic operations
main.py
python
1
2
3
4
5
6
#!/usr/bin/env python3
import sys
import json
# TODO: Implement counter with CAS for atomic updates