Code
memcached
# gets returns a unique cas token as the last value
gets counter
# VALUE counter 0 2 14
# 42
# END
# ^ cas_unique = 14
# cas — write only if cas_unique still matches
cas counter 0 0 2 14
43
# STORED (token 14 still current)
# Another client modified counter between our gets and cas:
cas counter 0 0 2 14
44
# EXISTS (token changed — someone else wrote first)
# Race-free increment pattern
gets counter # 42, token=14
# ... compute new value ...
cas counter 0 0 2 14
43
# if EXISTS, retry: gets again, recompute, cas again
# Python (pymemcache)
from pymemcache.client.base import Client
c = Client(("localhost", 11211))
result = c.gets("counter") # (value, cas)
ok = c.cas("counter", b"43", result[1], expire=0)
if not ok:
pass # retry