Hello,CSDN的各位小伙伴们,又见面啦!今天我们要学习的例程是:Event Latency!我们开始吧!
例程背景
今天这个example比较好玩,有点类似于网络中的通信。我们要实现的是一个简单的point-to-point的消息收发机制。其中,sender源源不断地通过电缆cable给另一端的receiver发送消息,然而消息在电缆中的传输是有延迟的,因此我们还需要模拟这一种延迟。而我们需要思考的则是如何把这种延迟的建模和收发双发的processes分离开。
例程代码分析
我们跳过基本的头文件和参数设置:
import simpy
SIM_DURATION = 100
接下来,我们对电缆进行建模,我们思考一下电缆cable类中需要有什么功能呢?第一个我们能够发送消息到电缆上;第二,能够模拟消息传输过程中的延迟;第三,接收方能够从电缆上获取数据。为了实现功能1、3,我们就需要使用simpy中的store资源了:
class Cable:
def __init__(self, env, delay):
self.env = env
self.delay = delay
self.store = simpy.Store(env)
def latency(self, value):
yield self.env.timeout(self.delay) # 模拟传输过程中的时延
self.store.put(value) # 向电缆中传输数据
def put(self, value):
self.env.process(self.latency(value))
def get(self):
return self.store.get() # 从电缆中获取数据
基本上比较重要的点都在注释上了,但是还有一个特别值得关注的是:在latency函数中,yield self.env.timeout(self.delay)
和self.store.put(value)
这两句的顺序是不能调换的。不然就无法体现延迟的效果。
接下来,我们来看看收发双方怎么写:
def sender(env, cable):
while True:
yield env.timeout(5) # 表示每隔多久发包一次
cable.put(f'Sender sent this message at {
env.now}')
收方:
def receiver(env, cable):
while True:
msg = yield cable.get() # 注意要有 "yield"
print('Receive the message: { ', msg, ' } at: ', env.now)
最后启动仿真,如下:
print('EXAMPLE 4: EVENT LATENCY')
env = simpy.Environment()
cable = Cable(env, 10)
env.process(sender(env, cable))
env.process(receiver(env, cable))
env.run(until=SIM_DURATION)
输出的效果为:
EXAMPLE 4: EVENT LATENCY
Receive the message: { Sender sent this message at 5 } at: 15
Receive the message: { Sender sent this message at 10 } at: 20
Receive the message: { Sender sent this message at 15 } at: 25
Receive the message: { Sender sent this message at 20 } at: 30
Receive the message: { Sender sent this message at 25 } at: 35
Receive the message: { Sender sent this message at 30 } at: 40
Receive the message: { Sender sent this message at 35 } at: 45
Receive the message: { Sender sent this message at 40 } at: 50
Receive the message: { Sender sent this message at 45 } at: 55
Receive the message: { Sender sent this message at 50 } at: 60
Receive the message: { Sender sent this mes