Reputation: 711
Qt's documentation states that all QDateTime functions are reentrant which in Qt terms it means that if you create new object of QDateTime in another thread you can safely work with it. But are the following static members thread safe: QDateTime::currentDateTime and QDateTime::fromTime_t?
Code in a secondary thread:
// Is line below thread safe?
QDateTime tDateTimeNow1 = QDateTime::currentDateTime();
// The below code should be no different then the one above..
QDateTime tDateTimeNow2;
tDateTimeNow2 = tDateTimeNow2.currentDateTime();
I'm confused by the following statement in this article http://doc.qt.nokia.com/4.7-snapshot/thread-basics.html : "QDateTime::currentDateTime() isn't marked as thread-safe in Qt documentation, however we can get away with using it in this small example because we know that the QDateTime::currentDateTime() static method isn't used in any other threads."
If QDateTime::currentDateTime() cannot be used in secondary threads than how can we create QDateTime object with current date time in a thread safe manner?
Here are other static member functions similar like the one above that I don't know if they can be safely used in threads: 1) QTimer::singleShot 2) QString::fromUtf8 3) QString:number
Upvotes: 1
Views: 1752
Reputation: 4772
If you need a thread-safe way to get a QDateTime object with the current time, create a function that guards the unsafe call.
QDateTime getCurrentTime()
{
static QMutex mutex;
QMutexLocker locker(&mutex);
return QDateTime::currentDateTime();
}
Upvotes: 4