用了Event依旧死锁

自学python线程进程遇到的一个小白问题——用了Event依旧死锁

一,准备用Event实现生产者消费者模型

import random
import threading
import time
from queue import Queue
items = []
event = threading.Event()
class consumer(threading.Thread):
    def __init__(self, items, event):
        threading.Thread.__init__(self)
        self.items = items
        self.event = event
    def run(self):
        for i in range(5):
            time.sleep(2)
            self.event.wait()
            item = self.items.pop()
            print("consumer : %d 被消费 by %s %s" %(item, self.name, time.ctime()))
class producer(threading.Thread):
    def __init__(self, items, event):
        threading.Thread.__init__(self)
        self.items = items
        self.event = event
    def run(self):
        global item
        for i in range(5):
            time.sleep(2)
            item = random.randint(0, 256)
            self.items.append(item)
            print("producer: %d 被生产 by %s %s" %(item, self.name, time.ctime()))
            #self.event.set()
            #self.event.clear()
            self.event.set()
            self.event.clear()
if __name__ == "__main__":
    t1 = consumer(items, event)
    t2 = producer(items, event)
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print("结束 了")

一开始我是这么写的,这么一看肯定是没有问题,可是运行起来缺不尽人意,能不能成功全靠运气,也改了不少地方,看是不是自己理解错了,都没有改善,最后我把消费者的时间延迟改为1,就再也没有出过死锁的现象了。用了一段时间遇到的坑,和大家分享一下。遇到了,也不至于花费太久时间。
第一次写这玩意,不是很熟练,多多包涵,欢迎批评指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值