forked from Answeror/lit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.py
262 lines (219 loc) · 6.55 KB
/
worker.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from collections import deque
from qt.QtCore import (
Qt,
QMetaObject,
QThread,
QObject,
Slot,
Q_ARG,
QMutex,
QMutexLocker
)
import heapq
import itertools
class Action(QObject):
def __init__(self, impl, finished=None, failed=None, main=False, priority=0):
super(Action, self).__init__()
self.impl = impl
self._finished = finished
self._failed = failed
self.main = main
self.priority = priority
@Slot()
def finished(self):
if self._finished:
self._finished()
self.deleteLater()
@Slot(object)
def failed(self, e):
if self._failed:
self._failed(e)
self.deleteLater()
@Slot()
def run(self):
try:
self.impl()
if self.main:
self.finished()
else:
QMetaObject.invokeMethod(
self,
'finished',
Qt.QueuedConnection
)
except Exception as e:
if self.main:
self.failed(e)
else:
QMetaObject.invokeMethod(
self,
'failed',
Qt.QueuedConnection,
Q_ARG(object, e)
)
class Make(QObject):
def __init__(self, impl, finished=None, failed=None, main=False, priority=0):
super(Make, self).__init__()
self.impl = impl
self._finished = finished
self._failed = failed
self.main = main
self.priority = priority
@Slot(object)
def finished(self, result):
if self._finished:
self._finished(result)
self.deleteLater()
@Slot(object)
def failed(self, e):
if self._failed:
self._failed(e)
self.deleteLater()
@Slot()
def run(self):
try:
result = self.impl()
if self.main:
self.finished(result)
else:
QMetaObject.invokeMethod(
self,
'finished',
Qt.QueuedConnection,
Q_ARG(object, result)
)
except Exception as e:
if self.main:
self.failed(e)
else:
QMetaObject.invokeMethod(
self,
'failed',
Qt.QueuedConnection,
Q_ARG(object, e)
)
class Job(QObject):
def __init__(self, impl):
super(Job, self).__init__()
self.impl = impl
@Slot()
def run(self):
self.impl.run()
self.deleteLater()
class Pool(object):
def __init__(self):
self.thread = QThread()
self.thread.start()
self.local = QObject()
self.remote = QObject()
self.remote.moveToThread(self.thread)
def start(self, job):
job.setParent(self.local)
job = Job(job)
job.moveToThread(self.thread)
job.setParent(self.remote)
QMetaObject.invokeMethod(
job,
'run',
Qt.QueuedConnection
)
def clear(self):
for job in self.local.children():
if hasattr(job, 'cancel'):
job.cancel()
class Heap(object):
REMOVED = '<removed-task>' # placeholder for a removed task
def __init__(self):
self.mutex = QMutex()
self.clear()
def push(self, task, priority=0):
'Add a new task or update the priority of an existing task'
with QMutexLocker(self.mutex):
if task in self.entry_finder:
self.remove(task)
count = next(self.counter)
entry = [priority, count, task]
self.entry_finder[task] = entry
heapq.heappush(self.pq, entry)
def remove(self, task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
with QMutexLocker(self.mutex):
entry = self.entry_finder.pop(task)
entry[-1] = self.REMOVED
def pop(self):
'Remove and return the lowest priority task. Raise KeyError if empty.'
with QMutexLocker(self.mutex):
while self.pq:
priority, count, task = heapq.heappop(self.pq)
if task is not self.REMOVED:
del self.entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')
def clear(self):
self.pq = [] # list of entries arranged in a heap
self.entry_finder = {} # mapping of tasks to entries
self.counter = itertools.count() # unique sequence count
def __bool__(self):
return bool(self.pq)
class Worker(QObject):
def __init__(self):
super(Worker, self).__init__()
#self.q = deque()
self.q = Heap()
self.pool = Pool()
@Slot()
def deal(self):
try:
job = self.q.pop()
except:
pass
else:
if _getattr(job, 'main', False):
job.run()
else:
self.pool.start(job)
if self.q:
self.delay_deal()
def clear(self):
self.q.clear()
self.pool.clear()
def delay_deal(self):
QMetaObject.invokeMethod(
self,
'deal',
Qt.QueuedConnection
)
def do(self, **kargs):
"""Do some asyne job, maybe in main thread."""
if 'make' in kargs:
make = kargs['make']
catch = kargs.get('catch', lambda x: x)
job = Make(
make,
catch,
main=kargs.get('main', False),
priority=kargs.get('priority', 0)
)
elif 'action' in kargs:
action = kargs['action']
react = kargs.get('react', lambda: None)
job = Action(
action,
react,
main=kargs.get('main', False),
priority=kargs.get('priority', 0)
)
elif 'job' in kargs:
job = kargs['job']
_check_job(job)
else:
assert False, 'Wrong arguments.'
self.q.push(job, -_getattr(job, 'priority', 0))
self.delay_deal()
def _getattr(target, name, default):
return getattr(target, name) if hasattr(target, name) else default
def _check_job(job):
assert isinstance(job, QObject)
assert hasattr(job, 'run')