Python 线程 条件锁 生产者消费者模型

原文链接: Python 线程 条件锁 生产者消费者模型

上一篇: Python 线程 实现 循环定时器和延时器

下一篇: tf rnn 延时序列 滚动序列和反转序列

创建多个生产者和消费者,并且加上条件锁,避免线程冲突

import threading
from threading import Thread
from threading import Condition

import time
import random

c = Condition()  # 条件锁
itemNum = 0
item = 0


def consumer():  # 消费者
    global item  # 商品编号
    global itemNum
    c.acquire()  # 锁住资源
    while 0 == itemNum:  # 如无产品则让线程等待
        print("consumer :挂起.", threading.current_thread().name, threading.current_thread())
        c.wait()
    itemNum -= 1
    print("consumer : 消费 %s." % item, itemNum, threading.current_thread().name, threading.current_thread())
    c.release()  # 解锁资源


def producer():  # 生产者
    global item  # 商品编号
    global itemNum
    time.sleep(3)
    c.acquire()  # 锁住资源
    item = random.randint(1, 1000)
    itemNum += 1
    print("producer : 生产 %s." % item, threading.current_thread().name, threading.current_thread())
    c.notifyAll()  # 唤醒所有等待的线程--》其实就是唤醒消费者进程
    c.release()  # 解锁资源


threads = []  # 线程收集列表

for i in range(0, 4):  # 使用循环完成生产者与消费者线程的建立
    t1 = Thread(target=producer, name=f'pro_{i}')
    t2 = Thread(target=consumer, name=f"cos_{i}")
    t1.start()
    t2.start()
    threads.append(t1)
    threads.append(t2)

for t in threads:  # 等待所有线程完成
    t.join()

生产和 消费的线程不一定是创建时对应的

consumer :挂起. cos_0 <Thread(cos_0, started 4612)>
consumer :挂起. cos_1 <Thread(cos_1, started 12068)>
consumer :挂起. cos_2 <Thread(cos_2, started 6504)>
consumer :挂起. cos_3 <Thread(cos_3, started 9400)>
producer : 生产 543. pro_0 <Thread(pro_0, started 6900)>
producer : 生产 590. pro_1 <Thread(pro_1, started 7084)>
consumer : 消费 590. 1 cos_3 <Thread(cos_3, started 9400)>
consumer : 消费 590. 0 cos_1 <Thread(cos_1, started 12068)>
consumer :挂起. cos_2 <Thread(cos_2, started 6504)>
consumer :挂起. cos_0 <Thread(cos_0, started 4612)>
producer : 生产 121. pro_2 <Thread(pro_2, started 4036)>
consumer : 消费 121. 0 cos_2 <Thread(cos_2, started 6504)>
consumer :挂起. cos_0 <Thread(cos_0, started 4612)>
producer : 生产 799. pro_3 <Thread(pro_3, started 5892)>
consumer : 消费 799. 0 cos_0 <Thread(cos_0, started 4612)>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值