7 ms·
Wandering progressively off-topic... I wouldn't call it "copious", necessarily. It's easily reusable, at least. My aforementioned cooperative multitasking hack
by camccann 17y ago
Wandering progressively off-topic...
I wouldn't call it "copious", necessarily. It's easily reusable, at least. My aforementioned cooperative multitasking hackery involved inheriting from a base "coroutine-able" class that, among other things, kept a per-instance execution stack that would be updated by the dispatching loop depending on the value yielded by the generator. The end result would look something like this:
def foo(self):
spam = 1
while True:
yield self.call(self.spam_and_eggs, spam)
spam += 1
def spam_and_eggs(self, spam):
print ("spam, " * spam) + "and eggs"
if spam >= 20:
yield self.halt()
else:
yield self.wait(2)
yield self.ret()
Which would print another item off the menu every other cycle of the dispatcher loop, until 20 "spams" at which point the "thread" would stop.
Other actions included a goto (clear the stack and jump to a new generator method), conditional waits (keep running the thread unless, say, 2 miliseconds have elapsed since it started this cycle), and "message passing" between threads (push something onto another instance's stack). The main downside was that stack traces from exceptions inside a faux-thread were singularly useless, though I was working on some debugging tools for code using it.
The guts of it amounted to maybe a few hundred lines of code, most of which is the dispatch loop and bookkeeping for message queues. One of these days I ought to clean it up and post the code on the web somewhere, but unfortunately I'm currently in a somewhat sticky spot and looking for work (and I fear that spending more time on things like building cooperative multitasking in Python than things to further my humdrum day-job career has not been a great help thus far).