djangomemcachedpython-memcached

Memcached Compare-And-Set pattern yields wrong result


I'm trying to implement memcached compare-and-set pattern, following the instructions of Guido at:

http://neopythonic.blogspot.nl/2011/08/compare-and-set-in-memcache.html

However, I don't seem to get it right and I have no idea what's wrong. The files below use Django (1.4.5 Final) and python-memcache (1.48).

settings.py

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

djangocache.py

#!/usr/bin/env python
from django.core.cache import cache
import multiprocessing.dummy

django_key = "TEST"
cached_key = cache.make_key(django_key).encode("UTF-8")

def add_to_cache(item):
    client = cache._cache
    #client = cache._lib.Client(cache._servers)

    while True:
        items = client.gets(cached_key)
        if client.cas(cached_key, items+(item,)):
            break

if __name__ == "__main__":
    cache.set(django_key, ())

    p = multiprocessing.dummy.Pool(2)
    p.map(add_to_cache, range(10))
    print(len(cache.get(django_key)))

Running it:

mzialla@Q330 ~/test $ DJANGO_SETTINGS_MODULE=settings python djangocache.py
5

It occasionally outputs 6, 7, etc. like you would expect when dealing with race conditions. I've tried multiple client instantiations (see comment).

Help?


Solution

  • python-memcached disables cas by default. Enable it by adding

     client.cache_cas = True
    

    to your code.

    Credits to Nate Thelen, who's comment I discovered right after asking this question.