Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/ka_task.py
blob: b18212ba245e7031cb083a469e8914f3363cd606 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# coding: UTF8
# Copyright 2009 Thomas Jourdan
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import sys
import threading
import gobject
import ka_debug

#gtk.gdk.threads_init()

_internal_lock = threading.Lock()
_internal_task_count = 0

def _enter():
    """
    pre: _internal_task_count >= 0
    post: _internal_task_count >= 1
    """
    _internal_lock.acquire()
    global _internal_task_count
    _internal_task_count += 1
    _internal_lock.release()

def _leave():
    """
    pre: _internal_task_count >= 1
    post: _internal_task_count >= 0
    """
    _internal_lock.acquire()
    global _internal_task_count
    _internal_task_count -= 1
    _internal_lock.release()

def is_completed():
    """
    pre: _internal_task_count >= 0
    """
    global _internal_task_count
    return _internal_task_count < 1

class GeneratorTask(object):

    def __init__(self, task_function, on_task_completed):
        """
        pre: task_function is not None and callable(task_function)
        pre: on_task_completed is not None and callable(on_task_completed)
        """
        self._on_task_completed = on_task_completed
        self._task_function = task_function

    def _start(self, *args, **kwargs):
        try:
            _enter()
            result = self._task_function(*args)
            print 'result', result
            gobject.idle_add(self._on_task_completed, result)
        except:
            ka_debug.err('failed calculating [%s] [%s] [%s]' % \
                    (self._task_function, sys.exc_info()[0], sys.exc_info()[1]))
        finally:
            _leave()

    def start(self, *args, **kwargs):
        threading.Thread(target=self._start, args=args, kwargs=kwargs).start()