Python并发编程研究【一】

本文介绍了使用Python实现多线程编程中锁、可重入锁及条件变量的应用,并展示了如何利用Redis实现分布式锁,确保分布式环境下的数据一致性。

多线程(锁/可重入锁/线程同步)/ 分布式锁

import time
import redis
import threading


# redis连接池
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True)
r = redis.StrictRedis(connection_pool=pool)

queue = []

# 普通锁,不允许一个线程内被多次acquire,会出现死锁
# lock = threading.Lock()
# 可重入锁,允许一个线程内被多次acquire,acquire/release必须成对出现
lock = threading.RLock()
product = None
con = threading.Condition()


def thread_lock_task():
    # 线程锁
    lock.acquire()

    queue.append(1)

    print('{} 获取锁 len(queue)={}'.format(
        threading.currentThread().name,
        len(queue)
    ))

    lock.release()


def distributed_lock_task():
    # redis提供分布式锁
    with r.lock(name='queue', timeout=30, blocking_timeout=30):
        queue.append(1)
        print('{} 获取锁 len(queue)={}'.format(
            threading.currentThread().name,
            len(queue)
        ))


def produce():
    # 线程同步;生产者
    global product

    if con.acquire():
        while True:
            if product is None:
                print('produce')
                product = 'something'
                # con.notify() # 唤起一个挂起线程,不会释放占用锁
                con.notify_all() # 唤起全部挂起线程,不会释放占用锁

            con.wait() # 释放占用锁,当前线程被挂起,直到收到通知或超时
            time.sleep(2)


def consume():
    # 线程同步;消费者
    global product

    if con.acquire():
        while True:
            if product is not None:
                print('comsume')
                product = None
                con.notify()

            con.wait()
            time.sleep(2)


t1 = threading.Thread(target=produce)
t2 = threading.Thread(target=consume)
t1.start()
t2.start()

 

转载于:https://www.cnblogs.com/codechord/p/9505712.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值