1

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 Answers3

2

Use an atomic counter for your nonce:

QString Class1::getNonce()
{
    static std::atomic<unsigned long long> counter;
    return QString::number(counter++);
}
Casey
  • 41,449
  • 7
  • 95
  • 125
2

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.

phyatt
  • 18,472
  • 5
  • 61
  • 80
1

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