Question

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.

Was it helpful?

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.

OTHER TIPS

Use an atomic counter for your nonce:

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

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top