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

CONCURRENCY_CACHE = 2
NTHREADS = 10
NOPS = 10000

def test1():
    cache = redis.Redis(host='localhost',port=6379,db=CONCURRENCY_CACHE)
    for i in range(NOPS//NTHREADS):
        hot = int(cache.get("hot"))
        hot = hot + 1
        cache.set("hot", hot)
    cache.close()

def test3():
    cache = redis.Redis(host='localhost',port=6379,db=CONCURRENCY_CACHE)
    for i in range(NOPS//NTHREADS):
        with cache.pipeline() as pipe:
            while True:
                try:
                    pipe.watch("hot")
                    pipe.multi()
                    hot = int(cache.get("hot"))
                    hot = hot + 1
                    pipe.set("hot", hot)
                    pipe.execute()
                    pipe.unwatch()
                    break
                except redis.WatchError:
                    pass
    cache.close()

def test4():
    cache = redis.Redis(host='localhost',port=6379,db=CONCURRENCY_CACHE)
    for i in range(NOPS//NTHREADS):
        cache.incrby("hot", 1)
    cache.close()

def test(lbl, f):
    cache = redis.Redis(host='localhost',port=6379,db=CONCURRENCY_CACHE)
    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)
