2013-12-20 24 views
1

我只是想執行下面的代碼。QMutex,如果線程在運行,請在此等待

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

即使我用互斥鎖寫不同的線程得到相同的現時。我怎麼解決這個問題? 謝謝。

+0

是互斥的靜態?或者你只使用Class1的一次實例? – drescherjm

+0

是的,它是在Class1中作爲QMutex互斥體;而我只是使用互斥這個功能。 –

+2

也許是因爲'QDateTime :: currentDateTime'只有毫秒分辨率? –

回答

2

我更喜歡使用QMutexLocker的。

Class1::Class1() 
{ 
    m_mutex = new QMutex(); 

} 

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

希望有幫助。

2

,將原子計數器的當前值:

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

感謝您的所有郵件我用這樣的方式

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