#!/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()
python3 阻塞队列实现
最新推荐文章于 2023-05-09 16:09:50 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)