
Originally Posted by
caduel
where have you read that?
In Qt4 you can either:
* work with blocking I/O (not in the gui thread, as otherwise your app freezes til the I/O is over)
* work with non-blocking I/O: you need a QEventLoop running in your thread - you may use the main (i.e. gui) thread, but you do not have to.
HTH
Here is a sample code to illustrate the problem I have encountered. I made it as brief as possible. Hence, it is not going with the best practice. Please forgive me for that.
#include <QtNetwork/QTcpServer>
#include <QtCore/QThread>
#include <QtCore/QCoreApplication>
#include <iostream>
#include <assert.h>
class ServerThread
: public QThread{
Q_OBJECT
public:
, mpServer(0)
{}
void run ()
{
bool lbOk(connect(mpServer, SIGNAL(newConnection()),
this, SLOT(onNewConnection())));
assert(lbOk);
}
private:
protected slots:
void onNewConnection()
{
std::cout << "new connection!" << std::endl;
}
};
int main(int argc, char *argv[])
{
ServerThread lrThread(0);
// lrThread.start();
lrThread.run();
return a.exec();
}
#include <QtNetwork/QTcpServer>
#include <QtCore/QThread>
#include <QtCore/QCoreApplication>
#include <iostream>
#include <assert.h>
class ServerThread : public QThread
{
Q_OBJECT
public:
ServerThread(QObject *ipParent)
: QThread(ipParent)
, mpServer(0)
{}
void run ()
{
mpServer = new QTcpServer();
bool lbOk(connect(mpServer, SIGNAL(newConnection()),
this, SLOT(onNewConnection())));
assert(lbOk);
mpServer->listen(QHostAddress::Any, 8888);
}
private:
QTcpServer* mpServer;
protected slots:
void onNewConnection()
{
std::cout << "new connection!" << std::endl;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ServerThread lrThread(0);
// lrThread.start();
lrThread.run();
return a.exec();
}
To copy to clipboard, switch view to plain text mode
It runs fine with expected outcome which print a message every time a connection is made.
However, if the line 40 is uncommented and line 41 commented, the ServerThread::onNewConnection() method is never called with connections made.
It stops working while the QTcpServer is not created on the main thread.
Bookmarks