python3 阻塞队列实现

该博客展示了如何使用Python的threading库实现一个带阻塞的队列,即MyBlockingQueue。这个队列在满时会阻止生产者继续添加元素,在空时会阻止消费者获取元素。通过两个ConsumerThread类的实例消费队列,一个ProducerThread实例生产队列,展示了线程间的同步与通信。博客还包含了一个简单的多线程运行示例。
摘要由CSDN通过智能技术生成
#!/usr/bin/python

from typing import List
import threading
import time

class MyBlockingQueue:
    def __init__(self, capability: int):
        self.capability = capability
        self.lock = threading.Lock();
        self.notFull = threading.Condition(self.lock);
        self.notEmpty = threading.Condition(self.lock);
        self.list = []

    def put(self, obj):
        self.lock.acquire()

        while (len(self.list) == self.capability):
            self.notFull.wait()
        self.list.append(obj)

        self.notEmpty.notify()
        self.lock.release()

    def get(self):
        self.lock.acquire()

        while (len(self.list) == 0):
            self.notEmpty.wait()

        obj = self.list.pop(0)

        self.notFull.notify()
        self.lock.release()
        return obj

    def size(self):
        self.lock.acquire();

        size = len(self.list)

        self.lock.release()
        return size

class ConsumerThread(threading.Thread):
    def __init__(self, name: str, blockingQ: MyBlockingQueue):
        threading.Thread.__init__(self);
        self.name = name
        self.blockingQ = blockingQ

    def run(self):
        print("开始线程:" + self.name);

        i = 0
        while (True):
            val = self.blockingQ.get()
            print('{0} {1}: get {2} from queue'.format(self.name, i, val))
            i = i + 1
            time.sleep(0.5)
        return

class ProducerThread(threading.Thread):
    def __init__(self, name: str, blockingQ: MyBlockingQueue):
        threading.Thread.__init__(self);
        self.name = name
        self.blockingQ = blockingQ

    def run(self):
        print("开始线程:" + self.name);

        i = 0
        while (True):
            self.blockingQ.put(i)
            print('{0} {1}: put {1} from queue'.format(self.name, i))
            i = i + 1
            time.sleep(0.5)
        return

blockingQ = MyBlockingQueue(10)
consumer1 = ConsumerThread("Con1", blockingQ)
consumer2 = ConsumerThread("Con2", blockingQ)
producer1 = ProducerThread("Pro1", blockingQ)


producer1.start()

time.sleep(6)

consumer1.start()
consumer2.start();

consumer1.join()
consumer2.join()
producer1.join()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值