QAbstractSocket :: waitForDisconnected是否会产生竞争条件?

时间:2015-12-13 21:01:17

标签: qt

以下是我的QTcpread子类的概述,该子类由我的QTcpServer子类按连接创建

void
Socket :: run ()
{
    QTcpSocket socket;

    if (false == socket .setSocketDescriptor (m_sd))
    {
         error ();
         return;
    }

    do_stuff ();

    socket .disconnectFromHost ();
    socket .waitForDisconnected ();
}

我收到此错误:

QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState

咦?此代码从the documentation解除。在其他地方我看到了这个:

socket .disconnectFromHost ();

if (QAbstractSocket :: ConnectedState == socket .state ())
    socket .waitForDisconnected (); 

这不是竞争条件吗?如果它不是竞争条件,那么它不是异步过程,在该范围内disconnectFromHost将永远成功,waitForDisconnected将是多余的。正确?

这些功能的正确用法是什么?

1 个答案:

答案 0 :(得分:0)

有一种情况QAbstractSocket::disconnectFromHost会立即断开连接。如果你看一下source code,就有这一部分:

...
    // Wait for pending data to be written.
    if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
        || d->socketEngine->bytesToWrite() > 0)) {
        ...
        if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
        if (!d->disconnectTimer) {
            d->disconnectTimer = new QTimer(this);
            connect(d->disconnectTimer, SIGNAL(timeout()), this,
                SLOT(_q_forceDisconnect()), Qt::DirectConnection);
        }
        if (!d->disconnectTimer->isActive())
            d->disconnectTimer->start(2000);
        }
        d->socketEngine->setWriteNotificationEnabled(true);

#if defined(QABSTRACTSOCKET_DEBUG)
        qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
#endif
        return;
    } else {
#if defined(QABSTRACTSOCKET_DEBUG)
        qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
#endif
    }
}

SocketState previousState = d->state;
d->resetSocketLayer();
d->state = UnconnectedState;
...

因此,如果没有要写入的待处理数据,它将立即断开连接。