Sympy_intro

# countdown.py

#

# A simple generator function

def countdown(n):

    print "Counting down from", n

    while n > 0:

        yield n

        n -= 1

    print "Done counting down"

# Example use

if __name__ == '__main__':

    for i in countdown(10):

        print i

yield In Python language.

In C language:

int function(void) {     int i;     for (i = 0; i < 10; i++)         return i;   /* won't work, but wouldn't it be nice */ }

def gen(header, footer):

        yield header

        for thing in q:

                yield thing

        yield footer

q = [1, 2, 3, 4]

for tmp in gen('something','anything'):

    print(tmp)

===============================

/usr/bin/python -u  "/home/barnix2/py/simpy/coroutine3"

something

1

2

3

4

anything

from __future__ import generators # Python 2.2 only

from SimPy.Simulation import *

from random import uniform

class Car(Process):

    def __init__(self,id):

        Process.__init__(self)

        self.id=id

    def carDriving(self,driveTime):

        # the Process Execution Method (generator)

        print "%5.1f %s started" %(now(),self.id)

        yield hold,self,driveTime

        print "%5.1f %s arrived" %(now(),self.id)

initialize()

nrCars=10

for i in range(nrCars):

    c=Car(id="Car %s" %i)

    activate(c,c.carDriving(driveTime=uniform(1,90)))

simulate(until=100)

from __future__ import generators

from SimPy.Simulation import *

from random import uniform

# Python 2.2 only

class Car(Process):

    def __init__(self,id):

        Process.__init__(self)

        self.id=id

    def carParking(self,driveTime,parkTime): # the PEM

        yield hold,self,driveTime

        yield request,self,parkingLot

        # begin Mutex section

        print "%5.1f %s gets space" %(now(),self.id)

        yield hold,self,parkTime

        print "%5.1f %s releases space" %(now(),self.id)

        yield release,self,parkingLot

# end Mutex section

nrCars=10

initialize()

parkingLot=Resource(capacity=4,qType=FIFO)

for i in range(nrCars):

    c=Car(id="Car %s" %i)

    activate(c,c.carParking(driveTime=10,parkTime=uniform(5,20)))

simulate(until=100)