c++qtmutexqmutex

QMutex ,wait here if a thread is in function


I just want to implement the code like below.

QString Class1::getNonce()
{
    //if some thread is getting nonce wait here until it finishes the its own job.
    mutex.lock();
    QString nonce=QString("%1").arg(QDateTime::currentDateTime().toTime_t());
    mutex.unlock();
    return nonce;    
}

even I write with mutex different threads get same nonce. How can I solve this problem? Thanks.


Solution

  • I prefer the use of a QMutexLocker.

    Class1::Class1()
    {
        m_mutex = new QMutex();
    
    }
    
    QString Class1::getNonce()
    {
        static int counter = 0;
        QMutexLocker locker(m_mutex);
        counter++;
        return QString::number(counter);
    }
    

    Hope that helps.