#!/usr/bin/env python
# lemmings.py from sip015.py (and sms015)
# 2002 Sept 15 modified to use SimPy with resources (91a)
# 2004 December simplified and updated. Removed unit tests
# $Revision: 1.1.1.1 $ $Author: kgmuller $ $Date: 2005/01/15 15:16:52 $

from __future__ import generators
from SimPy.Simulation import *
from random import Random,expovariate,uniform

""" Lemmings with a gatekeeper using SimPy

    This is essentially a simulation of an M/M/1 queue.
    It just produces a trace; no monitoring is attempted.
"""
__version__='\nModel: lemmings.py'

g = Random(333555)

class Generator(Process):
    """ generates Lemmings at random """

    def execute(self,maxNumber,MeanInterval):
        for i in range(maxNumber):
            L = Lemming("Lemming "+`i`)
            activate(L,L.execute(),delay=0)
            yield hold,self,g.expovariate(1.0/MeanInterval)

gateKeeper=Resource(name='Gatekeeper')

class Lemming(Process):
    """ Lemmings request a gatekeeper and hold it for an exponential time """
        
    def execute(self):       
        print "%7.4f %s says Hello World"%(now(),self.name)
        yield request,self,gateKeeper
        print "%7.4f %s At last  "%(now(), self.name)
        yield hold,self,3.3
        yield release,self,gateKeeper
        print "%7.4f %s says Geronimo  "%(now(), self.name)

def main():
    print __version__
    initialize()
    g = Generator('Generator')
    activate(g,g.execute(maxNumber=10,MeanInterval=1.0))
    simulate(until=10.0)

main()

