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
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
原文:https://www.cnblogs.com/max520liuhu/p/12556159.html