Recursos Compartilhados¶
Simpy fornece 3 tipos de resources que o ajudam a modelar suas simulações, onde múltiplos processos podem usar um recurso com capacidade limitada ( ex., carros em um posto com uma limitada quantidade de bombas ) ou o clássico problema produtor-consumidor.
Nesta seção, faremos uma breve introdução da classe Resource da biblioteca do Simpy.
Uso básico da classe Resource¶
Faremos uma modificação simples no nosso processo do carro elétrico car que foi criado na última seção.
O carro agora irá para uma bcs (estação de carga da baterias) e solicitar 1 dos 2 charing spots (pontos de carga). Porém se todos os pontos estiverem em uso, ele aguarda a liberação de um deles. Só então quando um estiver liberado, obviamente, deve começar a carregar a bateria e assim deixar a estação:
>>> def car(env, name, bcs, driving_time, charge_duration):
... # Simulate driving to the BCS
... yield env.timeout(driving_time)
...
... # Request one of its charging spots
... print('%s arriving at %d' % (name, env.now))
... with bcs.request() as req:
... yield req
...
... # Charge the battery
... print('%s starting to charge at %s' % (name, env.now))
... yield env.timeout(charge_duration)
... print('%s leaving the bcs at %s' % (name, env.now))
O método de Resource request() gera um evento que permite que você aguarde até que o recurso fique disponível novamente. Se você começar a usar o recurso, você terá direito a uso do mesmoi até que você o release (libere).
Caso utilize o recurso usando a declaração with como demonstrado a seguir, o recurso é automaticamente liberado. Porém se você chamar o método request() sem declarar with, você assume a responsabilidade de chamar o método release() quando você terminar de usar o recurso.
When you release a resource, the next waiting process is resumed and now “owns”
one of the resource’s slots. The basic
Resource sorts waiting processes in a FIFO
(first in—first out) way.
A resource needs a reference to an Environment and
a capacity when it is created:
>>> import simpy
>>> env = simpy.Environment()
>>> bcs = simpy.Resource(env, capacity=2)
We can now create the car processes and pass a reference to our resource as
well as some additional parameters to them:
>>> for i in range(4):
... env.process(car(env, 'Car %d' % i, bcs, i*2, 5))
<Process(car) object at 0x...>
<Process(car) object at 0x...>
<Process(car) object at 0x...>
<Process(car) object at 0x...>
Finally, we can start the simulation. Since the car processes all terminate on their own in this simulation, we don’t need to specify an until time—the simulation will automatically stop when there are no more events left:
>>> env.run()
Car 0 arriving at 0
Car 0 starting to charge at 0
Car 1 arriving at 2
Car 1 starting to charge at 2
Car 2 arriving at 4
Car 0 leaving the bcs at 5
Car 2 starting to charge at 5
Car 3 arriving at 6
Car 1 leaving the bcs at 7
Car 3 starting to charge at 7
Car 2 leaving the bcs at 10
Car 3 leaving the bcs at 12
Note that the first two cars can start charging immediately after they arrive at the BCS, while cars 2 and 3 have to wait.
What’s Next¶
You should now be familiar with SimPy’s basic concepts. The next section shows you how you can proceed with using SimPy from here on.