Search code examples
pythonsimulationsimpy

Simpy Simulation with Blocking


I have a simple simulation in Simpy. The flow is the following: arrivals -> resource1 -> resource2 -> exit. The process is in series, that is, customers have to go first to resource 1 and then to resource 2. I want the buffer size of resource 2 to be zero. That is, if resource 2 is full, customer should wait in resource 1 until resource 2 is available. Is there a simple way to do this? I thought that the resource function would have a parameter like "queue_size" or something like that but it does not.


Solution

  • sounds like you want your entity to successfully seize resource 2 before releasing resource 1. You may want to skip the with syntax and use the base request and release methods.

    import simpy
    
    def a_process(env, id, p1, p2):
    
        print(env.now, id, 'start')
        print(env.now, id, 'grabbing resource 1')
    
        r1 = p1.request()
        yield r1
        print(env.now, id, 'got resource 1')
    
        print(env.now, id, 'start some stuff')
        yield env.timeout(9)
        print(env.now, id, 'finish doing stuff')
    
        print(env.now, id, 'grabbing resouse 2')
        r2 = p2.request()
        yield r2
        print(env.now, id, 'got resource 2')
    
        print(env.now, id, 'releasing resouce 1')
        yield p1.release(r1)
        print(env.now, id, "released resource 1")
    
        print(env.now, id, 'doing some more stuff')
        yield env.timeout(11)
        print(env.now, id, 'done doing more stuff')
    
        print(env.now, id, 'releasing resouce 2')
        yield p2.release(r2)
        print(env.now, id, 'released resource 2 and is done')
    
    
    
    env = simpy.Environment()
    p1 = simpy.Resource(env, capacity=1)
    p2 = simpy.Resource(env, capacity=1)
    
    for i in range(5):
        env.process(a_process(env, i + 1, p1, p2))
    
    env.run()