00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #include "workerthread.h"
00024
00025 namespace farsa {
00026
00027 WorkerThread::WorkerThread( QObject* parent ) :
00028 QThread(parent),
00029 operations(),
00030 mutex(),
00031 waitForOperationsToDo(),
00032 operation(NULL),
00033 quitRequested(false),
00034 exceptions() {
00035 }
00036
00037 WorkerThread::~WorkerThread() {
00038 foreach (BaseException *e, exceptions) {
00039 delete e;
00040 }
00041 }
00042
00043 void WorkerThread::addOperation( ThreadOperation* newOperation ) {
00044 mutex.lock();
00045 operations.enqueue( newOperation );
00046 mutex.unlock();
00047 if ( operations.size() == 1 ) {
00048
00049 waitForOperationsToDo.wakeAll();
00050 }
00051 }
00052
00053 void WorkerThread::stopCurrentOperation() {
00054 mutex.lock();
00055 if ( operation ) {
00056 operation->stop();
00057 }
00058 mutex.unlock();
00059 }
00060
00061 void WorkerThread::run() {
00062 forever {
00063 mutex.lock();
00064
00065
00066
00067 if ( quitRequested ) {
00068 mutex.unlock();
00069 return;
00070 }
00071 if ( operations.size() == 0 ) {
00072
00073 waitForOperationsToDo.wait( &mutex );
00074 }
00075 if ( quitRequested ) {
00076 mutex.unlock();
00077 return;
00078 }
00079 operation = operations.dequeue();
00080 mutex.unlock();
00081 try {
00082 operation->run();
00083 } catch (BaseException& e) {
00084 BaseException* cloned = e.clone();
00085 exceptions.append(cloned);
00086
00087 emit exceptionDuringOperation(cloned);
00088 } catch (...) {
00089 UnknownException* e = new UnknownException();
00090 exceptions.append(e);
00091
00092 emit exceptionDuringOperation(e);
00093 }
00094 mutex.lock();
00095 delete operation;
00096 operation = NULL;
00097 mutex.unlock();
00098 if ( quitRequested ) {
00099 return;
00100 }
00101 }
00102 }
00103
00104 void WorkerThread::quit() {
00105 mutex.lock();
00106 quitRequested = true;
00107 mutex.unlock();
00108 stopCurrentOperation();
00109 waitForOperationsToDo.wakeAll();
00110 wait();
00111 }
00112
00113 }