【问题标题】:Python SimPy - Request resource for certain time, if not given then quitPython SimPy - 请求资源一段时间,如果没有给出则退出
【发布时间】:2021-09-30 16:53:57
【问题描述】:

所以基本上,要请求资源并且在等待时,如果 X 秒内没有资源给予请求,我们基本上什么都不做。“客户没有得到帮助”等。

来自他们的示例代码:

print('%s arrives at the carwash at %.2f.' % (name, env.now))
with cw.machine.request() as request:
    yield request

所以.. 当它请求 cw.machine.request() 时,只在删除请求之前执行一定的持续时间,例如不做任何事情。

print('%s arrives at the carwash at %.2f.' % (name, env.now))
with cw.machine.request() as request:
    waiting for X seconds before exiting... is it a continous loop or how does it work?

    yield request

【问题讨论】:

    标签: python simpy


    【解决方案1】:

    我认为您的示例是 simpy 示例的一部分。要在进程(事件)之间实现条件,可以使用:

    &| 运算符 ---> 示例:yield first_process & second_process

    AnyOf() AllOf()simpy.events 命名空间中提供 ---> 示例:yield AnyOf(env, list_of_events)

    关于一次等待多个事件的更多信息:READ THIS

    此外,您可以中断另一个进程,捕获中断异常,并在进程中断时做任何您想做的事情。 READ THIS

    我尝试按照您要求的方式完成资源请求:

    with self.machine.request() as request:
        print(f"{car.name} requested machine at {self.env.now}")
        # waiting_threshold for 45 time
        waiting_threshold = self.env.timeout(45)
    
        # yield request or waiting_threshold, whichever happens earlier
        yield request | waiting_threshold
    
        # if (didn't get the resource) or waiting_threshold is triggered:
        if not request.triggered:
            # Interrupt washing process
            print(f"{car.name} has waited enough. Leaving carwash at {self.env.now}.")
        else:
            print(f"{car.name} started to be washed at {self.env.now}")
            # washing time 30
            yield self.env.timeout(30)
            print(f"{car.name} finished to be washed at {self.env.now}")
    

    【讨论】:

    • 您好,感谢您的帮助。这正是我发现并解决问题的方法。 100% 正确!谢谢。
    • @PPP 不客气。请将此答案标记为解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2011-08-29
    相关资源
    最近更新 更多