Re: QTcpSockets and QThreads
Quote:
Originally Posted by TheRonin
What doesn't work:
Calling the closeConnectionNow()-method from the parent thread does not have any effect. It executes but the socket refuses to close.
Sounds like you are calling the function directly from another thread. This is a no no. So basically, I'm afraid you have two parallel executions going in the code above: 1) the actual thread execution is blocked in the end of the run()-method at QSocket::waitForDisconnected() and 2) another thread (where closeConnectionNow() is called from) executes closeConnectionNow().
You might want to consider entering to an event loop in the thread and using signals and slots and a queued connection instead of a direct call from another thread.
So the code should look more like this:
Code:
// create a queued connection between the thread and the parent
Thread* thread = new Thread(this);
connect(this, SIGNAL(somethingHappened()), thread, SLOT(closeConnection()), Qt::QueuedConnection);
// ..and when you would call closeConnectionNow(), now you will just emit somethingHappened() instead
// remember to declare somethingHappened() as a signal
emit somethingHappened();
// declare Thread::closeConnectionNow() as a slot
void Thread::closeConnectionNow()
{
socket->disconnectFromHost();
}
void Thread::run()
{
...
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
connect(socket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
exec(); // enter to the event loop
}
Re: QTcpSockets and QThreads
Thanks for the tip! I changed the structure and now it works fine! :D
Just one thing though; when i have more threads running, won't emiting somethingHappened() cause all of them to close?
Re: QTcpSockets and QThreads
Quote:
Originally Posted by TheRonin
Just one thing though; when i have more threads running, won't emiting somethingHappened() cause all of them to close?
Yes it will unless you map the signal somehow to the appropriate thread (check QSignalMapper docs).
Another a bit simplier way could be to simply pass some identifier number (eg. socket descriptor) as an argument for the signal and then the thread closes connection only if the identifier matches.