python实现生产者消费者多线程程序,三个生产者负责随机生成100以内自然数并随机加减乘除,然后把算式发给消费者,消费者计算并打印结果
时间: 2024-02-19 18:29:46 浏览: 107
以下是一个简单的多线程生产者-消费者模型的实现,其中有三个生产者负责随机生成100以内的自然数并随机加减乘除,然后把算式发给消费者,消费者计算并打印结果。代码如下:
```python
import threading
import queue
import random
# 生产者类
class Producer(threading.Thread):
def __init__(self, task_queue):
super(Producer, self).__init__()
self.task_queue = task_queue
def run(self):
for i in range(100):
a = random.randint(1, 100)
b = random.randint(1, 100)
operator = random.choice(['+', '-', '*', '/'])
task = f"{a} {operator} {b}"
self.task_queue.put(task)
print("生产者任务已完成")
# 消费者类
class Consumer(threading.Thread):
def __init__(self, task_queue):
super(Consumer, self).__init__()
self.task_queue = task_queue
def run(self):
while True:
task = self.task_queue.get()
if task == None:
break
result = eval(task)
print(f"{task} = {result}")
print("消费者任务已完成")
if __name__ == "__main__":
task_queue = queue.Queue()
# 创建三个生产者
producers = [Producer(task_queue) for i in range(3)]
# 创建一个消费者
consumer = Consumer(task_queue)
# 启动所有生产者和消费者线程
for p in producers:
p.start()
consumer.start()
# 等待所有生产者线程完成
for p in producers:
p.join()
# 将None加入队列,通知消费者线程退出
task_queue.put(None)
# 等待消费者线程完成
consumer.join()
print("所有任务已完成")
```
运行结果如下:
```
13 + 27 = 40
54 + 48 = 102
57 / 14 = 4.071428571428571
77 + 44 = 121
36 - 80 = -44
...
消费者任务已完成
所有任务已完成
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)