~mshinke/nvdajp/betterJtalk

« back to all changes in this revision

Viewing changes to source/synthDrivers/_bgthread.py

refactored _bgthread and _nvdajp_jtalk

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# _bgthread.py 
 
2
# -*- coding: utf-8 -*-
 
3
#A part of NonVisual Desktop Access (NVDA)
 
4
#Copyright (C) 2006-2010 NVDA Contributors <http://www.nvda-project.org/>
 
5
#Copyright (C) 2010-2012 Takuya Nishimoto (nishimotz.com)
 
6
#This file is covered by the GNU General Public License.
 
7
#See the file COPYING for more details.
 
8
#
 
9
# based on NVDA (synthDrivers/_espeak.py)
 
10
 
 
11
from logHandler import log
 
12
import threading
 
13
import Queue
 
14
 
 
15
bgThread = None
 
16
bgQueue = None
 
17
isSpeaking = False
 
18
 
 
19
class BgThread(threading.Thread):
 
20
        def __init__(self):
 
21
                threading.Thread.__init__(self)
 
22
                self.setDaemon(True)
 
23
 
 
24
        def run(self):
 
25
                global isSpeaking
 
26
                while True:
 
27
                        func, args, kwargs = bgQueue.get()
 
28
                        if not func:
 
29
                                break
 
30
                        try:
 
31
                                func(*args, **kwargs)
 
32
                        except:
 
33
                                log.error("Error running function from queue", exc_info=True)
 
34
                        bgQueue.task_done()
 
35
 
 
36
def execWhenDone(func, *args, **kwargs):
 
37
        global bgQueue
 
38
        # This can't be a kwarg in the function definition because it will consume the first non-keywor dargument which is meant for func.
 
39
        mustBeAsync = kwargs.pop("mustBeAsync", False)
 
40
        if mustBeAsync or bgQueue.unfinished_tasks != 0:
 
41
                # Either this operation must be asynchronous or There is still an operation in progress.
 
42
                # Therefore, run this asynchronously in the background thread.
 
43
                bgQueue.put((func, args, kwargs))
 
44
        else:
 
45
                func(*args, **kwargs)
 
46
 
 
47
def initialize():
 
48
        global bgThread, bgQueue
 
49
        bgQueue = Queue.Queue()
 
50
        bgThread = BgThread()
 
51
        bgThread.start()
 
52
 
 
53
def terminate():
 
54
        global bgThread, bgQueue
 
55
        bgQueue.put((None, None, None))
 
56
        bgThread.join()
 
57
        bgThread = None
 
58
        bgQueue = None