PDA

View Full Version : Threads creatoin and execution?



probine
23rd March 2006, 09:04
Using Qt-4.1.1.

I have looked at the documentation, and there is an exameple on how to create a thread inheriting from QThread. The problem is that I cannot see how to apply the example in this class:
_______________________________________________--
# Server.h
# ifndef SERVER_H
# define SERVER_H

# include <QObject>
# include "ServerGUI.h"

class Server : public QObject
{
Q_OBJECT

private:

public:
void run();

public slots:
void new_client();
};

# endif
________________________________________________--

# Server.cpp
# include <iostream>

# include "Server.h"

Server :: Server()
{

};


void Server :: new_client()
{
std::cout << "New client connected\n";
}

void Server :: run()
{
std::cout << "Thread running\n";
QThread::start(QThread::NormalPriority=QThread::In heritPriority);
}
_______________________________________________-

There is some more code about connecting the server and so on, but is not relevant now.

How do I start the thread ?

zlatko
23rd March 2006, 09:18
Your class must be inherit from QThread instead QObject and you also should reinplement protected method run() where must bee your needed for threading code. Read documentation !

probine
23rd March 2006, 09:23
I read the documentation.

QThread inherits from QObject, threfore I assume that I do not need to inherit from QThread again.

zlatko
23rd March 2006, 09:46
:) then read C++ documentation



/// Server.h
# ifndef SERVER_H
# define SERVER_H

# include <QThread>
# include "ServerGUI.h"

class Server : public QThread
{
Q_OBJECT

protected:
void run();

public slots:
void new_client();
};

# endif


/// Server.cpp
# include <iostream>
# include "Server.h"

Server :: Server()
{

};


void Server :: new_client()
{
std::cout << "New client connected\n";
}

void Server :: run()
{
std::cout << "Thread running\n";
}


Then after you create object Server call method start() and your thread will be started

wysota
23rd March 2006, 11:25
QThread inherits from QObject, threfore I assume that I do not need to inherit from QThread again.

Then you assume wrong. If QObject inherited QThread then this would be true, but not the other way round. All panda bears are animals but not all animals are panda bears, therefore "inheriting" an animal doesn't make you a panda bear (but inheriting a panda bear does make you an animal).