+class _WorkerThread(QtCore.QObject):
+
+ _taskComplete = qt_compat.Signal(object)
+
+ def __init__(self, futureThread):
+ QtCore.QObject.__init__(self)
+ self._futureThread = futureThread
+ self._futureThread._addTask.connect(self._on_task_added)
+ self._taskComplete.connect(self._futureThread._on_task_complete)
+
+ @qt_compat.Slot(object)
+ def _on_task_added(self, task):
+ if not self._futureThread._isRunning:
+ print "Dropping task"
+
+ func, args, kwds, on_success, on_error = task
+
+ try:
+ result = func(*args, **kwds)
+ isError = False
+ except Exception, e:
+ print "Error, passing it back to the main thread"
+ result = e
+ isError = True
+
+ taskResult = on_success, on_error, isError, result
+ self._taskComplete.emit(taskResult)
+
+
+class FutureThread(QtCore.QObject):
+
+ _addTask = qt_compat.Signal(object)
+
+ def __init__(self):
+ QtCore.QObject.__init__(self)
+ self._thread = QThread44()
+ self._isRunning = False
+ self._worker = _WorkerThread(self)
+ self._worker.moveToThread(self._thread)
+
+ def start(self):
+ self._thread.start()
+ self._isRunning = True
+
+ def stop(self):
+ self._isRunning = False
+ self._thread.quit()
+
+ def add_task(self, func, args, kwds, on_success, on_error):
+ assert self._isRunning, "Task queue not started"
+ task = func, args, kwds, on_success, on_error
+ self._addTask.emit(task)
+
+ @qt_compat.Slot(object)
+ def _on_task_complete(self, taskResult):
+ on_success, on_error, isError, result = taskResult
+ if not self._isRunning:
+ if isError:
+ print "Masking: %s" % (result, )
+ isError = True
+ result = StopIteration("Cancelling all callbacks")
+ callback = on_success if not isError else on_error
+ try:
+ callback(result)
+ except Exception:
+ print "Callback errored"
+
+
+class Producer(QtCore.QObject):