D
D
Denis2017-06-20 23:33:16
Qt
Denis, 2017-06-20 23:33:16

How to correctly delete a socket in a multi-threaded server based on QThreadPool?

There was a problem with freeing memory after disconnection when using QsslSocket::deleteLater(). I replaced the method call with delete socket and everything became ok, but the documentation advises using deleteLater(). The connection itself is handled in the run() method. The handler is inherited from QRunnable. Actually the question is why QsslSocket::deleteLater() does not work.

void RequestProcessor::run()
{

    /*QSslSocket **/socket = new QSslSocket();
    if (!socket) {
        qDebug("not enough memory to create new QSslSocket");
        return;
    }

    if (!socket->setSocketDescriptor(mSocketDescriptor))
    {
        qDebug("couldn't set socket descriptor");
        CloseSocket(socket);
        return;
    }

    socket->setProtocol(QSsl::AnyProtocol);
    socket->setPeerVerifyMode(QSslSocket::VerifyNone);

    startServerEncryption(socket);

    socket->waitForReadyRead();
    this->onReadyRead();

    socket->waitForDisconnected();
    socket->close();
    //socket->deleteLater();

    delete socket;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Sysolyatin, 2017-06-21
@D3Nd3R

The use of deleteLater() involves deferring deletion through the message queue of the thread that owns the object. In your case, this is the thread that executes the RequestProcessor::run(). If the thread terminates after run completes or its message queue is halted, the deletion itself may never occur.
Explicit deletion is perfectly acceptable in this case, since all the work on the socket is finished while you are waiting for the connection to complete.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question