1》请实现一个队列,队列的使用方有生产者(往队列里写数据),同时也有消费者(从里面取数据) 2)实现生产与消费的接口函数 3)需要考虑多线程环境,生产与消费可能同时进行的情况,导致数据不安全的问题
时间: 2023-05-26 15:06:27 浏览: 45
1. 实现一个基本的队列类,包含以下成员函数:
```python
class Queue:
def __init__(self):
self._items = []
self._lock = threading.Lock()
def enqueue(self, item):
with self._lock:
self._items.append(item)
def dequeue(self):
with self._lock:
if self.is_empty():
raise Exception("Queue is empty")
return self._items.pop(0)
def is_empty(self):
return len(self._items) == 0
```
其中使用了线程锁,保证在多线程环境下的数据安全。
2. 实现生产和消费的接口函数,以生产者写数据和消费者取数据为例:
```python
def producer(queue, item):
while True:
time.sleep(random.randint(1, 5))
queue.enqueue(item)
print(f"Produced: {item}")
def consumer(queue, name):
while True:
time.sleep(random.randint(1, 5))
try:
item = queue.dequeue()
print(f"Consumer-{name} consumed: {item}")
except Exception as e:
print(f"Consumer-{name} error: {e}")
```
其中使用了时间等待和随机数,模拟了生产和消费的过程。
3. 在多线程环境下,使用线程池来创建生产者和消费者线程进行测试:
```python
if __name__ == "__main__":
queue = Queue()
pool = ThreadPoolExecutor(max_workers=4)
futures = []
for i in range(2):
futures.append(pool.submit(producer, queue, i))
for i in range(2):
futures.append(pool.submit(consumer, queue, i))
wait(futures)
```
其中创建了2个生产者和2个消费者线程进行测试。
完整代码如下:
```python
import threading
from concurrent.futures import ThreadPoolExecutor, wait
import random
import time
class Queue:
def __init__(self):
self._items = []
self._lock = threading.Lock()
def enqueue(self, item):
with self._lock:
self._items.append(item)
def dequeue(self):
with self._lock:
if self.is_empty():
raise Exception("Queue is empty")
return self._items.pop(0)
def is_empty(self):
return len(self._items) == 0
def producer(queue, item):
while True:
time.sleep(random.randint(1, 5))
queue.enqueue(item)
print(f"Produced: {item}")
def consumer(queue, name):
while True:
time.sleep(random.randint(1, 5))
try:
item = queue.dequeue()
print(f"Consumer-{name} consumed: {item}")
except Exception as e:
print(f"Consumer-{name} error: {e}")
if __name__ == "__main__":
queue = Queue()
pool = ThreadPoolExecutor(max_workers=4)
futures = []
for i in range(2):
futures.append(pool.submit(producer, queue, i))
for i in range(2):
futures.append(pool.submit(consumer, queue, i))
wait(futures)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)