File: wb_background_thread.py

package info (click to toggle)
svn-workbench 1.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,164 kB
  • ctags: 2,111
  • sloc: python: 15,849; sh: 236; makefile: 11; ansic: 9
file content (56 lines) | stat: -rw-r--r-- 1,610 bytes parent folder | download | duplicates (2)
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
54
55
56
'''
 ====================================================================
 Copyright (c) 2003-2010 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
import locale

class BackgroundThread(threading.Thread):
    def __init__( self, app ):
        threading.Thread.__init__( self )

        self.setDaemon( 1 )
        self.running = 1
        self.app = app

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

    def run( self ):
        self.app.log.info( 'BackgroundThread thread %r' % (threading.currentThread(),) )
        self.app.log.info( 'BackgroundThread locale %r' % (locale.getlocale(),) )
        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()

    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