diff options
Diffstat (limited to 'ka_task.py')
-rw-r--r-- | ka_task.py | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/ka_task.py b/ka_task.py new file mode 100644 index 0000000..b18212b --- /dev/null +++ b/ka_task.py @@ -0,0 +1,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() |