PDA

View Full Version : How to use QThread::exec()



intensifi
10th February 2006, 07:20
Does anyone have any experience with this?

The QT 4.1 examples do not make use of this approach, but the Qthread class documentation shows pseudo code that does. I am drawn to this approach because I normally have my client in request/reply mode with a server, but sometimes the server sends data asynchronously on the socket.

Specifically I'd like to see an eaxmple that has the main run() function use QThread:exec() and have member functions for other threads to call to post requests to the server and have the thread receive messages from the server (QTCPSocket signals) , read tyhem correctly, parse them and emit signals for all server messages to anyone that might be listening.

As a side note, how about protecting the socket read and write functions separately as they are really two distinct pipes.

thanks in advance!

wysota
10th February 2006, 10:40
But what exactly is your question? QThread::exec() works the same as QCoreApplication::exec(), it starts an event queue processing.

intensifi
10th February 2006, 16:08
My question is how to have a QTcpSocket in the thread, use the socket to send requests to a server via methods callable from the GUI thread, have the thread listen for server messages and then create signals the GUI thread can be connected to obtain the server messages.

Cesar
10th February 2006, 16:57
Please, see Threaded Fortune Server Example (http://doc.trolltech.com/4.1/network-threadedfortuneserver.html) and Fortune Client Example (http://doc.trolltech.com/4.1/network-fortuneclient.html)

wysota
10th February 2006, 17:00
You don't need a separate thread for that... you can do this all in one thread. If you want to "call" methods of a separate thread from the "main" thread, it involves synchronisation between those two. You can use signals & slots for that and then it is as easy as connecting them and emitting a signal. But remember that it is all an event driven mechanism and two threads don't wait for each other here...

Some small partial example (this is not a Newbie section, so I expect you can fill the rest).

class MyThread : public QThread{
public:
void run(){
QTcpSocket *sock = new QTcpSocket;
connect(this, SIGNAL(sendToSocket(...)), sock, SLOT(...)));
// ...
exec();
}
// ...
};

MyThread *thr1;
//...
connect(thr1, SIGNAL(messageReceived(...)), this, SLOT(onMessageReceived(...)));
connect(this, SIGNAL(sendToThread(...)), thr1, SIGNAL(SendToSocket(...)));
thr1->start();