-
Notifications
You must be signed in to change notification settings - Fork 0
/
GLib_async_queue.py
62 lines (53 loc) · 2.34 KB
/
GLib_async_queue.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#
# Copyright (C) 2016 Jason Gray <jasonlevigray3@gmail.com>
#
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.
### END LICENSE
#Inspired by <https://gist.github.com/diosmosis/1132418> (Author name and License unknown),
#and <https://github.com/pithos/pithos/blob/master/pithos/gobject_worker.py>
#gobject_worker.py Copyright (C) 2010-2012 Kevin Mehall <km@kevinmehall.net>
#License GNU General Public License version 3.
import threading
import queue
import traceback
from gi.repository import GLib
__all__ = ['GLib_async_queue']
class Worker(threading.Thread):
def __init__(self):
super().__init__()
self.queue = queue.PriorityQueue()
self.fifo_priority = 0
self.daemon = True
self.start()
def run(self):
while True:
priority, _, f, args, kwargs, on_success, on_failure = self.queue.get()
try:
result = f(*args, **kwargs)
if on_success is not None:
GLib.idle_add(on_success, result, priority=priority)
except Exception as e:
if on_failure is not None:
e.traceback = traceback.format_exc()
error = 'Unhandled exception in GLib_async_queue call:\n{}'.format(e.traceback)
GLib.idle_add(on_failure, error, priority=priority)
def queue_task(self, priority, f, args, kwargs, on_success, on_failure):
self.fifo_priority += 1
self.queue.put((priority, self.fifo_priority, f, args, kwargs, on_success, on_failure))
worker = Worker()
def GLib_async_queue(on_success=None, on_failure=None, priority=GLib.PRIORITY_DEFAULT_IDLE):
def wrapper(f):
def run(*args, **kwargs):
worker.queue_task(priority, f, args, kwargs, on_success, on_failure)
return run
return wrapper