【SimPy系列博客之官方example学习与解读】—— Example 3: Car Wash

Hello,CSDN的各位小伙伴们,又见面啦!今天我们要学习的例程是:Car Wash!我们开始吧!

例程背景

这个例程相对于example 2来说会简单一些,有一个洗车厂,里面有若干台洗车机器,一台机器在一段时间内只能给一台车进行洗车服务。车辆陆陆续续到达洗车厂,如果有机器空闲,则开始为该车辆服务,如果没有机器空闲,则车辆会排队等待,直到有空闲的机器。

例程代码分析

照旧,基本的头文件和参数的定义我们就不赘述了:

import simpy
import random

RANDOM_SEED = 42
NUM_MACHINES = 2
WASHTIME = 5
T_INTER = 7
SIM_TIME = 20

下面我们先定义洗车厂,首先我们想洗车场有n个机器 ,每个机器自然就是建模成simpy中的resource。另外,洗车场还会有洗车的功能,洗车功能则需要花费一些时间。有了这些理解,我们可以直接写出洗车场的类:

class CarWash:
    # carwash里面包含了若干个机器,能够同时为车辆进行洗车服务

    def __init__(self, env, num_machines, washtime):
        self.env = env
        self.machine = simpy.Resource(env, capacity=num_machines)
        self.washtime = washtime

    def wash(self):
        yield self.env.timeout(self.washtime)  # 洗车需要花费的时间

下面我们来定义单一台车辆的行为,值得注意的是:车辆什么时候到达洗车场我们是不需要在车辆自己的建模中考虑的,应该把它分离出来,我们需要考虑的是车辆到达洗车场后,如何做:请求机器资源,然后开始洗车,然后释放机器资源并离开。所以我们可以写出车辆行为的代码:

def car(env, name, cw):
    print('Car: ', name, ' arrives at the carwash at: ', env.now)
    with cw.machine.request() as request:  # 请求机器资源
        yield request  # 等待洗车机
        print('Car: ', name, ' enters the carwash at: ', env.now)

        yield env.process(cw.wash())  # 开始洗车
        print('Car: ', name, ' leaves the carwash at: ', env.now)

with 跳出后,simpy会自动释放resource。最后,我们来简单定义一个车辆陆陆续续到达洗车场的函数即可:

def set_up(env, num_machines, washtime, t_inter):
    # 先创建一个carwash类
    carwash = CarWash(env, num_machines, washtime)

    i = 0
    # 初始有四辆车
    for _ in range(4):
        i += 1
        env.process(car(env, i, carwash))

    # 创建后续驶来的车辆
    while True:
        i += 1
        yield env.timeout(random.randint(t_inter - 2, t_inter + 2))
        env.process(car(env, i, carwash))

最后启动仿真:

print('EXAMPLE 3: CAR WAHS...')
random.seed(RANDOM_SEED)
env = simpy.Environment()
env.process(set_up(env, NUM_MACHINES, WASHTIME, T_INTER))
env.run(until=SIM_TIME)

仿真结果如下:

EXAMPLE 3: CAR WAHS...
Car:  1  arrives at the carwash at:  0
Car:  2  arrives at the carwash at:  0
Car:  3  arrives at the carwash at:  0
Car:  4  arrives at the carwash at:  0
Car:  1  enters the carwash at:  0
Car:  2  enters the carwash at:  0
Car:  5  arrives at the carwash at:  5
Car:  1  leaves the carwash at:  5
Car:  2  leaves the carwash at:  5
Car:  3  enters the carwash at:  5
Car:  4  enters the carwash at:  5
Car:  6  arrives at the carwash at:  10
Car:  3  leaves the carwash at:  10
Car:  4  leaves the carwash at:  10
Car:  5  enters the carwash at:  10
Car:  6  enters the carwash at:  10
Car:  5  leaves the carwash at:  15
Car:  6  leaves the carwash at:  15
Car:  7  arrives at the carwash at:  17
Car:  7  enters the carwash at:  17

你可能感兴趣的:(SimPy,学习,python)