Freeze and Resume execution

Brian Kelley bkelley at wi.mit.edu
Thu May 20 12:27:15 EDT 2004


Miki Tebeka wrote:

> Hello All,
> 
> I'm looking for a way to "yield" an exception.
> 
> Background: I'm writing a hardware simulator. I have an output buffer
> and need to freeze when it's full and then when called again to resume
> execution from the point where it stopped.
> 
> Currently all I can think of is to use a class and save the state when
> throwing an exception. However this required manual book keeping of the
> current state (and it is complicated).
> 
> I'd like to use generators but can't see any "nice" way of doing it.
> What I'd like it to throw an exception when the buffer is full and then
> next time the generator is called to continue execution as after a
> "yield".

I'm not sure if this helps or not, but as Peter was saying, throwing an 
exception is counter to resuming a state machine as raising an exception 
will halt execution.

You can however, yield exceptions through a generator, not raise them. 
I do this occasionally in threaded GUI work.  Here is a simple 
micro-thread inspired interrupt.  Note however, that the exception is 
syntactic sugar, you can (and maybe should) use your own class for 
managing your simulated hardware interrupts.

def work(res, length=10):
     while 1:
         if len(res) > length:
             # oops, need an interrupt to handle the
             # global state, the buffer is full
             yield ValueError("length > %s"%length)
         else:
             res.append(1)

l = []
g = iter(work(l, 10))

while 1:
     # work until an interrupt
     err = g.next()
     try:
         raise err
     except ValueError:
         print "clearing the list"
         del l[0:10]

> 
> Is this possible?
> Can you recommend a good way of doing this? Any state machine?
> 
> Thanks.
> Bye.
> --
> -------------------------------------------------------------------------
> Miki Tebeka <miki.tebeka at zoran.com>
> http://www.cs.bgu.ac.il/~tebeka
> The only difference between children and adults is the price of the toys.
> 
> 



More information about the Python-list mailing list