-2

The code is for a simulation of registration desk with 2 personnel and 10 students where, it takes 5 min to complete the registration and 3 min is the waiting period before the next student can start registration.

I m new to simulation and I fail to understand the purpose/use/working of code tagged as #line1 and #line2

Also, why doesn't the code execute first for the for loop before #line2?

 import simpy
    class Student(object):
      def __init__(self,env,reg):
        self.env=env
        self.action=env.process(self.run())       #line 1
        self.reg=reg
      def run(self):
        with reg.request() as r:
          yield r
          print("Start registration at at %d" % env.now)
          yield env.timeout(5)
          print("Start waiting at %d "% env.now)
          yield env.timeout(3)
    env=simpy.Environment()
    reg=simpy.Resource(env,capacity=2)
    student=Student(env,reg)
    for i in range (9):
      env.process(student.run())                   
    env.run(until=80)                              #line2
Lexs
  • 1

1 Answers1

1

#Line 2 is what actually starts the simulation for 80 units of time. The rest of the code sets up the simulation's starting state. This env.run() is not the run() defined in the Student class

#Line 1 is more interesting. There are a couple of patterns for doing simulations. one pattern uses classes and when a class object is instantiated/created it also starts its simulation process, so you would not need to call the student.run() yourself. The __init__() gets called when you create a class object. However if you use this pattern then the loop before #line 2 should be changed from

student = Student(env, reg)
for i in range(9):
    env.process(student.run())

to

students = [Student(env,reg) for _ in range(10)]

This will create 10 students, each waiting to register. The advantage of creating 10 students is each one can have individual states, like a unique id number, and collect stats about themselves. This is very useful in more complex simulations

This is how this code should have been written.

The other pattern is where you do call Student.run() yourself. To do that here you would comment out #line 1 and change the loop counter in the loop above #line 2 from 9 to 10. The disadvantage here is all your students are using the same class variables. A more common way of using this pattern is to not use a class, just a def function and call this function 10 times, passing the env, and reg directly to the function

As written, what this code is really doing is creating one student and that one student is registering 10 times, once when it is created, and then 9 more times in the loop. While this may demonstrate how a resource is used, I agree this code can be a bit confusing.

Michael
  • 1,671
  • 2
  • 4
  • 8