File: wb_background_thread.py

package info (click to toggle)
svn-workbench 1.5.0-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,400 kB
  • ctags: 1,585
  • sloc: python: 12,163; sh: 74; makefile: 46; ansic: 9
file content (53 lines) | stat: -rw-r--r-- 1,445 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
 ====================================================================
 Copyright (c) 2003-2006 Barry A Scott.  All rights reserved.

 This software is licensed as described in the file LICENSE.txt,
 which you should have received as part of this distribution.

 ====================================================================

    wb_background_thread.py

'''
import threading

class BackgroundThread(threading.Thread):
    def __init__( self ):
        threading.Thread.__init__( self )
        self.setDaemon( 1 )
        self.running = 1

        self.work_queue = []
        self.queue_lock = threading.Lock()
        self.queued_work_semaphore = threading.Semaphore( 0 )

    def run( self ):
        while self.running:
            # wait for work
            self.queued_work_semaphore.acquire()

            # dequeue
            self.queue_lock.acquire()
            function = self.work_queue.pop( 0 )
            self.queue_lock.release()

            # run the function
            function()

        print 'BackgroundThread.run() shutdown'

    def addWork( self, function ):
        # queue the function
        self.queue_lock.acquire()
        self.work_queue.append( function )
        self.queue_lock.release()

        # count one more piece of work
        self.queued_work_semaphore.release()

    def shutdown( self ):
        self.addWork( self.__shutdown )

    def __shutdown( self ):
        self.running = 0