简体   繁体   中英

Python SimPy - Request resource for certain time, if not given then quit

So basically, to request a resource and while it's waiting, if there is no resource given to the request for X seconds, we basically don't do anything.. "customer did not get help" etc.

From their example code:

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

So.. when it's requesting the cw.machine.request(), only do that for a certain duration before removing the request and for example not doing anything.

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

I think your example is a part of simpy's examples. To implement conditions between processes (events), you can use:

& and | operators ---> example: yield first_process & second_process

and

AnyOf() AllOf() provided in simpy.events namespace ---> example: yield AnyOf(env, list_of_events)

more about waiting for multiple events at once: READ THIS

Furthermore, you can interrupt another process, catch the interrupt exception, and do whatever you desire when a process is interrupted. READ THIS

I tried to complete the resource request the way you asked:

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM