PDA

View Full Version : Multithreaded server



virus
22nd February 2011, 17:57
I created two classes of FServer heir of QTcpServer and FThread from QThread. When you connect a new customer creates a separate thread, and it passes the handle to the socket.


void FServer::incomingConnection(int socketDescriptor)
{
FThread *thread = new FThread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(thread, SIGNAL(createNewSocket(QTcpSocket *)), this, SLOT(addNewSocket(QTcpSocket *)));
thread->start();
}
//SLOT
void FServer::addNewSocket(QTcpSocket *socket)
{
arraySockets.push_back(socket);

socket->moveToThread(QApplication::instance()->thread());
qDebug() << "FServer -> tcpSocket" << socket->thread();
}


The code runs in a separate thread:


void FThread::run()
{
QTcpSocket *tcpSocket = new QTcpSocket;

if (!tcpSocket->setSocketDescriptor(socketDescriptor)) {
emit error(tcpSocket->error());
return;
}

//My code ...............

emit createNewSocket(tcpSocket);

qDebug() << "FThread -> tcpSocket" << tcpSocket->thread();

tcpSocket->waitForDisconnected();
}

Error:


socket->moveToThread(QApplication::instance()->thread());

Text error:


QObject::moveToThread: Current thread (0x9707250) is not the object's thread (0x970fa88).


Why I can not I move objects in the main thread?

-------------------------
I came to the conclusion that everything can be processed without the use of threads.
Closed. Thank you.

e8johan
23rd February 2011, 07:28
Looking at the documentation for the method in question: http://doc.trolltech.com/4.7/qobject.html#moveToThread. The interesting bit is this:

Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.