利用Python语言的实现、建立Master,拥有两条队列。一条发布计算任务,一条接受结果。计算任务为对 100内的任意20个整数的阶乘计算。 2、建立Worker,实现对阶乘的计算。 3、运行时要求至少两个worker和一个master。
时间: 2024-02-18 13:04:36 浏览: 55
好的,下面是Python语言的实现代码:
Master程序:
```python
import pika
import random
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
channel.queue_declare(queue='result_queue', durable=True)
def callback(ch, method, properties, body):
print("Received %r" % body)
result = factorial(int(body))
ch.basic_publish(exchange='',
routing_key='result_queue',
body=str(result),
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
ch.basic_ack(delivery_tag=method.delivery_tag)
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
```
Worker程序:
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
channel.queue_declare(queue='result_queue', durable=True)
def callback(ch, method, properties, body):
print("Received %r" % body)
result = factorial(int(body))
ch.basic_publish(exchange='',
routing_key='result_queue',
body=str(result),
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
ch.basic_ack(delivery_tag=method.delivery_tag)
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
```
在运行时,你需要先启动两个Worker程序,然后启动Master程序。Master程序会向任务队列中发送20个计算任务,每个任务包含一个100以内的整数。Worker程序会从任务队列中获取任务,并计算阶乘。计算完成后,Worker程序会将结果发送到结果队列中,Master程序会从结果队列中获取结果,并输出到控制台中。
希望这个代码能够帮到你!
阅读全文