3

虽然这可行,但我有一种奇怪的感觉,我的 QObject 发出的不是线程安全的,而且它还没有爆炸的事实只是运气。

void LoginController::attemptLogin(QString username, QString password)
{
    emit loginAttemptStatus(QString("Connecting to service..."));
    QFuture<bool> future = QtConcurrent::run([&](QString username, QString password){
            // fake a long running operation
            QThread::sleep(1);
            emit loginAttemptStatus(QString("Connected to service..."));
            // a dumb test login
            QString u("asdf");
            bool success = username.compare( u ) == 0;
            if ( success ) {
                emit loginAttemptStatus(QString("Success..."));
            } else {
                emit loginAttemptStatus(QString("Failure..."));
            }
            return success;
    }, username, password);
    this->watchLoginAttempt.setFuture(future);
}

那么,捕获引用this会导致问题吗?

因为我认为是,但我找不到明确的答案。

4

2 回答 2

1

它可以爆炸的唯一情况是LoginController在 lambda 表达式结束之前销毁。正确处理watchLoginAttempt( future) 应该可以防止这种情况发生。

于 2013-12-02T16:05:04.043 回答
0

只要与插槽的连接不是QT::DirectConnectionQT::BlockingQueuedConnection 不同线程可能存在问题,则发射是线程安全的

connect默认情况下使用Qt::AutoConnection它确保无论哪个线程进行发射都采取正确的操作

于 2013-12-02T15:45:30.130 回答