QMutex ,wait here if a thread is in function

692 views Asked by At

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.

3

There are 3 answers

0
phyatt On BEST ANSWER

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.

0
Casey On

Use an atomic counter for your nonce:

QString Class1::getNonce()
{
    static std::atomic<unsigned long long> counter;
    return QString::number(counter++);
}
0
Veysel Bekir Macit On

Thank you for all messages I used a way like that

nonce=QDateTime::currentDateTime().toTime_t()+7500;

......

QString Class1::getNonce()
{
    QElapsedTimer timer;
    timer.start();

    mutex.lock();
    nonce+=timer.nsecsElapsed()/250;
    mutex.unlock();
    return QString("%1").arg(nonce);
}