Skip to content
Memcached

cas / gets — Compare-And-Swap

낙관적 락: 읽은 이후 변경되지 않은 경우에만 키 갱신.

#cas#gets#concurrency#locking

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