All pastes #487762 Raw Edit

Mine

public cpp v1 · immutable
·published 2007-05-14 17:02 UTC
rendered paste body
//thread.h#ifndef QTEAMSPEAKTHREAD_H#define QTEAMSPEAKTHREAD_H#include <QThread>#include <QMutex>#include <QWaitCondition>/**	@author Wladimir Leuschner <wladimir_leuschner@web.de>*/class Thread : public QThread{Q_OBJECTpublic:    Thread();    ~Thread();protected:    void run();private:    QMutex mutex;    QWaitCondition cond;    bool quit;    volatile int state;public slots:    void connectToServer();    void refresh();    void sendRequest();    void disconnectFromServer();signals:    void error(int socketError,const QString &message);};#endif---------------------------------------------------------------------------------------------------------------//thread.cpp#include "thread.h"#include <QMutexLocker>#include <QTextStream>#include <iostream>using namespace std;Thread::Thread() : QThread(){    state = 0;    quit = false;}void Thread::refresh(){    QMutexLocker locker(&mutex);    if(!isRunning())    {        start();    }    else    {        cond.wakeOne();    }}void Thread::connectToServer(){    QMutexLocker locker(&mutex);    state |= 1;    if(!isRunning())    {        start();    }    else    {        cond.wakeOne();    }}void Thread::sendRequest(){    QMutexLocker locker(&mutex);    state |= 2;    if(!isRunning())    {        start();    }    else    {        cond.wakeOne();    }}void Thread::disconnectFromServer(){    QMutexLocker locker(&mutex);    state |= 4;    if(!isRunning())    {        start();    }    else    {        cond.wakeOne();    }}void Thread::run(){    QMutexLocker locker(&mutex);    while(!quit)    {        mutex.lock();        if(state & 1)        {            cout<<"State 1"<<endl;            state |= 1;        }        mutex.unlock();        mutex.lock();        if(state & 2)        {            cout<<"State 2"<<endl;            state |=2;        }        mutex.unlock();        mutex.lock();        if(state & 4)        {            cout<<"state 3"<<endl;            state |=4;        }        mutex.unlock();        cond.wait(&mutex);    }}Thread::~Thread(){    quit = true;    cond.wakeOne();    wait();}-------------------------------------------------------------//main.cpp#include <QCoreApplication>#include "mainthread.h"#include "thread.h"#include <iostream>using namespace std;int main(int argc, char *argv[]){      QCoreApplication app(argc, argv);      mainThread mt;      Thread t;      QObject::connect(&mt,SIGNAL(connectTo()),&t,SLOT(connectToServer()));      QObject::connect(&mt,SIGNAL(disconnectFrom()),&t,SLOT(disconnectFromServer()));      QObject::connect(&mt,SIGNAL(sendReq()),&t,SLOT(sendRequest()));      while(1)      {          mt.getInput();      }      return 0;}