~ubuntu-branches/ubuntu/precise/gozerbot/precise

« back to all changes in this revision

Viewing changes to gozerbot/threadloop.py

  • Committer: Bazaar Package Importer
  • Author(s): Jeremy Malcolm
  • Date: 2008-06-02 19:26:39 UTC
  • mfrom: (1.1.3 upstream) (3.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080602192639-3rn65nx4q1sgd6sy
Tags: 0.8.1-1
New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# gozerbot/threadloop.py
 
2
#
 
3
#
 
4
 
 
5
""" class to implement start/stoppable threads """
 
6
 
 
7
__copyright__ = 'this file is in the public domain'
 
8
 
 
9
from gozerbot.generic import rlog
 
10
from gozerbot.thr import start_new_thread
 
11
import Queue
 
12
 
 
13
class ThreadLoop(object):
 
14
 
 
15
    def __init__(self, name):
 
16
        self.name = name
 
17
        self.stopped = False
 
18
        self.running = False
 
19
        self.outs = []
 
20
        self.queue = Queue.Queue()
 
21
 
 
22
    def _loop(self):
 
23
        rlog(5, self.name, 'starting loop')
 
24
        self.running = True
 
25
        while not self.stopped:
 
26
            data = self.queue.get()
 
27
            if self.stopped:
 
28
                return
 
29
            self.handle(*data)
 
30
        rlog(5, self.name, 'stopping loop')
 
31
 
 
32
    def put(self, *data):
 
33
        self.queue.put_nowait(data)
 
34
 
 
35
    def start(self):
 
36
        if not self.running:
 
37
            start_new_thread(self._loop, ())
 
38
 
 
39
    def stop(self):
 
40
        self.stopped = True
 
41
        self.queue.put(None)
 
42
 
 
43
    def handle(self):
 
44
        """ overload this """
 
45
        pass