CAS check and set

CAS stands for Check-And-Set or Compare-And-Swap. Memcached CAS command 'checks' and 'set' data item if and only if, no other client process has updated it since last read by this client.

當(dāng)我們想要在key = a, val = 2的時候?qū)al 設(shè)為4,我們首先要利用get來獲取2的hash結(jié)果,然后再使用這個2的hash結(jié)果來改變val = 4
舉例,

key = a, val = 3
# server1: want change a -> 4
3, Hash3 = gets(1)
# server2: want change a -> 5
3, Hash3 = gets(1)

# server1:
cas(a, 4,Hash3) # True, succeed

# server2:
cas(a, 5,Hash3) # False,Faile, because the hash of key a is now Hash(4) not Hash(3)

Implement CAS


CACHE = {}

#return True after setting the data
def set(key, value):
    CACHE[key] = value
    return True

#return the value for key
def get(key):
    return CACHE.get(key)

#delete key from the cache
def delete(key):
    if key in CACHE:
        del CACHE[key]

#clear the entire cache
def flush():
    CACHE.clear()

# QUIZ - implement gets() and cas() below
#return a tuple of (value, h), where h is hash of the value. a simple hash
#we can use here is hash(repr(val))
def gets(key):
    ###Your gets code here.
    v = get(key)
    if v:
        return v, hash(repr(v))
        
# set key = value and return True if cas_unique matches the hash of the value
# already in the cache. if cas_unique does not match the hash of the value in
# the cache, don't set anything and return False.
def cas(key, value, cas_unique):
    ###Your cas code here.
    r = gets(key)
    if r:
        val, unique = r
        if unique == cas_unique:
            return set(key, value)
        else:
            return False
    
#print set('x', 1)
#>>> True
#
#print get('x')
#>>> 1
#
#print get('y')
#>>> None
#
#delete('x')
#print get('x')
#>>> None
#
#set('x', 2)
#print gets('x')
#>>> 2, HASH
#
#print cas('x', 3, 0)
#>>> False
#
#print cas('x', 4, HASH)
#>>> True
#
#print get('x')
#>>> 4


References:
https://www.tutorialspoint.com/memcached/memcached_cas.htm

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容