#!/usr/bin/env python
from __future__ import generators
from SimPy.Simulation import *
from random import Random,expovariate,uniform
# 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.5 $ $Author: kgmuller $ $Date: 2006/02/02 13:35:45 $

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

