Persistent Threads & Synchronisation

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Nov 27 10:28:54 EST 2006


"Matthew Tylee Atkinson" <matthew at agrip.org.uk> wrote in message 
news:ekbtqe$74s$2 at news.freedom2surf.net...
>I appear to be having some problems with the isAlive() method of
> detecting if a thread is alive/active/running or not.  I'd be grateful
> for any advice.
>
Your comments about restartable threads got me thinking about generators. 
While this does not strictly do threading, this little example uses a list 
of generators, which save their state and pick up where they left off. 
(Also, look into simpy, which has a similar concept, but much more 
infrastructure support).

-- Paul


class Processor(object):
    def __init__(self, id_):
        self.id = id_
        self.finished = False

    def __str__(self):
        return "Processor: %s" % self.id

    def run(self):
        def runImpl_(self):
            runGen = self.runImpl()
            while not self.finished:
                try:
                    yield self.id,runGen.next()
                except StopIteration:
                    self.finished = True
        return runImpl_(self)

    def runImpl(self):
        times = 0
        while times < self.id:
            times += 1
            yield times


import random

class RandomProcessor(Processor):
    # just implement runImpl in subclass
    def runImpl(self):
        times = 0
        while times < self.id:
            times += 1
            yield random.random()

def main():
    # create list of processors
    procList =[ (random.choice([True,False]) and
                Processor(i) or RandomProcessor(i))
                for i in range(10)]
    procs = [ (p,p.run()) for p in procList ]

    # context switch loop
    while procs:

        # cycle through all processors
        for p in procs:
            try:
                ret = p[1].next()
                print ret
            except StopIteration:
                pass

        # remove any processors that have finished
        procs = [ p for p in procs if not p[0].finished ]

main()






More information about the Python-list mailing list