3

While this works, I have this strange feeling my QObject emit is not threadsafe and the fact that this hasn't exploded yet is just luck.

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);
}

So, does capturing a reference to this going to cause problems?

Because I think it is but I cannot find a definitive answer.

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
David Stocking
  • 1,200
  • 15
  • 26
  • 2
    `this` is never captured by reference, it can only be captured by value ([See "this" question](http://stackoverflow.com/questions/16323032/capturing-of-this-in-lambda?rq=1) [Get it, "this" question?!?]). – Casey Dec 02 '13 at 16:04
  • That makes sense otherwise we would need like some double dereference operator lol "this-->" – David Stocking Dec 03 '13 at 14:22

2 Answers2

1

The only case when it can explode, is when you destroy LoginController before lambda expression ends. Proper handling of watchLoginAttempt (future) should prevent this.

Marek R
  • 32,568
  • 6
  • 55
  • 140
0

emitting is thread-safe as long as the connections to the slots are not QT::DirectConnection or QT::BlockingQueuedConnection where there may be issues with different threads

connect uses Qt::AutoConnection by default which ensure the correct action is taken no matter which thread does the emitting

ratchet freak
  • 47,288
  • 5
  • 68
  • 106