Co-routines

Sean Ross frobozz_electric at hotmail.com
Thu Jul 17 10:20:29 EDT 2003


"Peter Hansen" <peter at engcorp.com> wrote in message
> I think the problem is underspecified.  What do you mean by the quoted
> phrase "lock-step"?

He wants to have f1 and f2 alternate executing instructions:

# pseudo code
def f1():
    instruction1-1
    instruction1-2

def f2():
    instruction2-1
    instruction2-2

So, for the code above, he would like to see something like the following
execution routine:

start execution of f1
execute instruction1-1
pause execution of f1
start execution of f2
execute instruction2-1
pause execution of f2
resume execution of f1
execute instruction1-2
pause execution of f1
resume execution of f2
execute instruction2-2
pause execution of f2

Do a piece of one, then do a piece of the other, then do another piece of
the former, and so on...

While the following code does not provide a solution to the OP's request, it
does show something very much like the behaviour that's being asked for.

class LockStepper:
    def __init__(self, id):
        self.id = id
        self.i = 1
        self.partner = None

    def next(self):
        if self.i > 10:
            return
        print "instruction %s-%s"%(self.id, self.i)
        self.i += 1
        self.partner.next()

f1 = LockStepper(1)
f2 = LockStepper(2)
f1.partner = f2
f2.partner = f1

# begin lock-step execution
f1.next()

The idea here is to think of each LockStepper as though it were a function,
and to think of the print statement in each of their next() methods as a
line of instruction inside the body of that function. The LockStepper
executes the first line of it's "function body", then pauses. It's partner
executes the first line of it's function body, then pauses. The partner's
partner was the original LockStepper, so it "resumes execution"
(self.partner.next()) and executes it's second line of instructions. And so
on...

If someone better at generators than I could put together a version of this
where the LockStepper's have a __call__() method that yields execution back
and forth between a partner LockStepper, then we'd be closer to simulating
the behaviour, but not to solving the problem, which asks for this behaviour
using arbitrary functions (not necessarily LockSteppers). And, I've know
idea how to do that :)

Hope that clears things up a little,
Sean






More information about the Python-list mailing list