S
S
Sazoks2020-07-13 18:23:13
Qt
Sazoks, 2020-07-13 18:23:13

Why can't I terminate the thread correctly?

Good day to all!
Problem such: I write the multithreaded network application on QT. The server has a given fixed number of threads. When a client connects, an object is created to work with that client and placed on the stream. When the client disconnects, the object emits a signal, at which the server should correctly stop this particular thread.
But at the moment of stopping and deleting the thread, it gives the following error:
QThread: Destroyed while thread is still running
Apparently, I don't understand how to properly stop a thread, and therefore I ask you to help!

Creating a new worker and a thread for it:

Workers[IndFreePlace] = new Worker(this->nextPendingConnection()->socketDescriptor(), IndFreePlace);
Threads[IndFreePlace] = new QThread(this);
Workers[IndFreePlace]->moveToThread(Threads[IndFreePlace]);

connect(Threads[IndFreePlace], &QThread::started, Workers[IndFreePlace], &Worker::StartWork);
connect(Workers[IndFreePlace], &Worker::StopThread, this, &Server::DisconnectClient);
Threads[IndFreePlace]->start();


Shutting down the client (DisconnectClient):
delete Workers[ThreadID];
Workers[ThreadID] = nullptr;

Threads[ThreadID]->quit();
Threads[ThreadID]->wait();
delete Threads[ThreadID];
Threads[ThreadID] = nullptr;

Without the Threads[ThreadID]->wait() line, it throws the error I posted above. With her, it just hangs and that's it.
Many thanks in advance to everyone for the replies! I hope for your help.

Payload code:
void Worker::StartWork()
{
    mUserSocket = new QTcpSocket;
    mUserSocket->setSocketDescriptor(mSockD);
    connect(mUserSocket, &QTcpSocket::disconnected, this, &Worker::StopWork);
    qDebug() << "Check\n";
}

The worker sends a signal to the server to stop the thread:
void Worker::StopWork()
{
    qDebug() << "Client #" << mID << " disconnected\n";

    mUserSocket->close();
    delete mUserSocket;
    mUserSocket = nullptr;
    emit StopThread(mID);
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question