-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator_task.py
39 lines (32 loc) · 1.11 KB
/
generator_task.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import _thread
import threading
from gi.repository import GLib
class GeneratorTask(object):
def __init__(self, generator, loop_callback, complete_callback=None):
self.generator = generator
self.loop_callback = loop_callback
self.complete_callback = complete_callback
self._stopped = False
self.__thread = None
def _start(self, *args, **kwargs):
self._stopped = False
for ret in self.generator(*args, **kwargs):
if self._stopped:
_thread.exit()
GLib.idle_add(self._loop, ret)
if self.complete_callback is not None:
GLib.idle_add(self.complete_callback)
def _loop(self, ret):
if ret is None:
ret = ()
if not isinstance(ret, tuple):
ret = (ret,)
self.loop_callback(*ret)
def start(self, *args, **kwargs):
self.__thread = threading.Thread(target=self._start, args=args, kwargs=kwargs)
self.__thread.daemon = True
self.__thread.start()
def stop(self):
self._stopped = True