# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from pymemcache.client.base import Client
import multiprocessing
import time

NTHREADS = 10 # CAS hangs for 100
NOPS = 10000

def test1():
    cache = Client(('localhost', 11211))
    for i in range(NOPS//NTHREADS):
        hot = int(cache.get("hot"))
        hot = hot + 1
        cache.set("hot", hot)
    cache.close()

def test3():
    cache = Client(('localhost', 11211))
    for i in range(NOPS//NTHREADS):
        while True:
            hot,tok = cache.gets("hot")
            hot = int(hot)
            hot = hot + 1
            if cache.cas("hot", hot, tok):
                break
    cache.close()

def test4():
    cache = Client(('localhost', 11211))
    for i in range(NOPS//NTHREADS):
        cache.incr("hot", 1)
    cache.close()

def test(lbl, f):
    cache = Client(('localhost', 11211))
    t1 = time.time()
    cache.set("hot", 0)
    t = []
    for i in range(NTHREADS):
        t.append(multiprocessing.Process(target=f, args=()))
    for i in range(NTHREADS):
        t[i].start()
    for i in range(NTHREADS):
        t[i].join()
    hot = int(cache.get("hot"))
    t2 = time.time()
    print("%s : %d = %d (%d ms)" % (lbl, hot, NOPS, (t2 - t1) * 1000))
    cache.close()

if __name__ == '__main__':
    test("No handling", test1)
    test("Replace with check", test3)
    test("Atomic increment", test4)
