Another question about writing non-blovking code

While I do understand how I can use imp.wakeup() or imp.onidle() to “open up” long loops so they don’t block, I’m often left feeling that my implementations could have been more elegant. As I’m not so familiar with object oriented languages I’m wondering if I’m missing some tricks that would make things tidier.

One reason that things become untidy to my eye is that variables have to have global scope in order to retain their values over successive calls. Relatively complex process with many parameters that factor into looping calculations (DSP type operations for example) end up requiring lots of global variables. Perhaps I’ve just developed an irrational dislike of globals.

When I first encountered the requirement for non-blocking imp code I was expecting to see a function along the lines of doEvents() as in VB to temporarily hand back cycles to the OS. I’m curious to know if there was a particular reason to avoid using this kind of mechanism? It certainly doesn’t appear to be possible to implement it using the calls available .

You can use local variables while still pausing in mid-function by using generators: there’s a quick precis here ora more in-depth treatment in the Dev Centre.

Peter

Thanks Peter, I think I’ve got it! That seems like a mighty powerful mechanism - much more so than the simple “doEvents” kind of call I was searching for. Hopefully anyone else searching with the same sort of antiquated terminology I’m familiar with will find this now. I wonder if it might help to link to the subject in the “See Also” section for imp.wakeup()

I’m guessing the choice of “generator” and “yield” has to do with the fact that yield can return a result. I found the example under the heading “Return Values” particularly interesting - no timers are involved, the loop presumably streams values out to the resume assignment as fast as the code can be executed inclusive, of course, of any other pending processes.

In that example, “loopsteps” is not a blocking function, because it contains a yield, but the while loop (which repeatedly resumes it) will block network messages etc. until it has run all ten times.

Similarly in the one under “Automatic Looping”, the whole program runs in one go (the “foreach” loop is blocking until the generator expires). Those two examples are examples of how generators work in general, not specifically of how to write non-blocking loops.

Peter