Distributed - lock -1.1 multi-threaded lock insatiable scene

Carried out against a remote computing wish a value increments by one, batch add ten times, the end result increased by 10 than the original

Unlock code does not meet the requirements

import threading, time, redis
from redis import StrictRedis


def increase_num(redis_conn, key):
    value = redis_conn.get(key)  # 获取数据
    time.sleep(0.1)
    if value:
        value = int(value) + 1
    else:
        value = 0
    redis_conn.set(key, value)
    thread_name = threading.current_thread().name
    print(thread_name, value)


##主程序
if __name__ == "__main__":
    pool = redis.ConnectionPool(host='192.168.200.136', port=6379, db=8)
    redis_pool = StrictRedis(connection_pool=pool)
    lock_key = 'test_key'
    thread_count = 10
    for i in range(thread_count):
        thread = threading.Thread(target=increase_num, args=(redis_pool, lock_key))
        thread.start()

#结果 是几乎同时操作
Thread-4 24
Thread-2 24
Thread-1 24
Thread-6 24
Thread-5 24
Thread-3 24
Thread-10 24
Thread-9 24
Thread-7 24
Thread-8 24


Solution: use of multi-threading mechanism for sharing the lock, the lock for the operating target

import threading, time, redis
from redis import StrictRedis


def increase_num(redis_conn, key):
    lock.acquire()
    try:
        value = redis_conn.get(key)  # 获取数据
        time.sleep(0.1)
        if value:
            value = int(value) + 1
        else:
            value = 0
        redis_conn.set(key, value)
        thread_name = threading.current_thread().name
        print(thread_name, value)
    except Exception as e:
        pass
    finally:
        lock.release()

##主程序
if __name__ == "__main__":
    pool = redis.ConnectionPool(host='192.168.200.136', port=6379, db=8)
    redis_pool = StrictRedis(connection_pool=pool)
    lock_key = 'test_key'
    lock = threading.Lock()
    thread_count = 10
    for i in range(thread_count):
        thread = threading.Thread(target=increase_num, args=(redis_pool, lock_key))
        thread.start()

#结果 符合预期
Thread-1 25
Thread-2 26
Thread-3 27
Thread-4 28
Thread-5 29
Thread-6 30
Thread-7 31
Thread-8 32
Thread-9 33
Thread-10 34

Here are some key for redis plus one operating just examples, for the corresponding operations can be redis redis method, where the lock mechanism is multi-threaded shared memory to achieve ten threads are on the same service running, and there is no thread isolation operation,

One problem encountered in practice, when you deploy high-availability cluster, each service has a timed script that needs to run every day, but just want to have a day to run, other cluster service discovery gave up a run when running Timing script task, this time how to achieve a shared communication multi-threaded give me what inspired? How to design a distributed lock up? See Section II

Guess you like

Origin www.cnblogs.com/max520liuhu/p/12556159.html