| Store | Cart

[Tutor] Good threading tutorial

From: Vicki Stanfield <vic...@stanfield.net>
Wed, 31 Mar 2004 15:15:46
> How about a nice "hello threads" example? :-)>
How about this one?

-----
import threading

class TaskThread(threading.Thread):
    """Thread that executes a task every N seconds"""

    def __init__(self):
        threading.Thread.__init__(self)
        self._finished = threading.Event()
        #self._interval = 15.0
        self._interval = 5.0
        self.num = 0

    def setInterval(self, interval):
        """Set the number of seconds we sleep between executing our task"""
        self._interval = interval

    def shutdown(self):
        """Stop this thread"""
        self._finished.set()

    def run(self):
        while 1:
            if self._finished.isSet(): return
            self.task()

            # sleep for interval or until shutdown
            self._finished.wait(self._interval)

    def task(self):
        """The task done by this thread - override in subclasses"""
        pass

if __name__ == '__main__':

    global num

    class printTaskThread(TaskThread):
        def task(self):
            print 'running %d' %self.num
            self.num = self.num + 1
            time.sleep(3)

    tt = printTaskThread()
    tt.setInterval(3)
    print 'starting'
    tt.start()
    print 'started, wait now'
    import time
    time.sleep(60)
    print 'killing the thread'
    tt.shutdown()
    print 'killed and done'
-------

I played with it a while back to get the feel of threads in Python.

--vicki


"A pessimist sees the difficulty in every opportunity; an optimist sees
the opportunity in every difficulty."
  --  Winston Churchill

Recent Messages in this Thread
Doug...@ge.com ) (Shawhan, Doug (EM, ITS) Mar 31, 2004 01:54 pm
Vicki Stanfield Mar 31, 2004 03:15 pm
Gregor Lingl Mar 31, 2004 04:17 pm
Messages in this thread