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

NTHREADS = 100
NOPS = 10000

def test1():
    cli = Client()
    cli.connect('localhost', 10800)
    cache = cli.get_or_create_cache('concurrency_cache')
    for i in range(NOPS//NTHREADS):
        hot = cache.get('hot')
        hot = hot + 1
        cache.put('hot', hot)
    cli.close()

def test3():
    cli = Client()
    cli.connect('localhost', 10800)
    cache = cli.get_or_create_cache('concurrency_cache')
    for i in range(NOPS//NTHREADS):
        done = False
        while not done:
            hot1 = cache.get('hot')
            hot2 = hot1 + 1
            done = cache.replace_if_equals('hot', hot1, hot2)
    cli.close()

def test(lbl, f):
    cli = Client()
    cli.connect('localhost', 10800)
    cache = cli.get_or_create_cache('concurrency_cache')
    t1 = time.time()
    cache.put('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 = cache.get('hot')
    t2 = time.time()
    print('%s : %d = %d (%d ms)' % (lbl, hot, NOPS, (t2 - t1) * 1000))
    cli.close()

if __name__ == '__main__':
    test('No handling', test1);
    # locking not supported using thin
    test('Replace with check', test3);
    # atomic increment not supported using thin
