Qt库-静态成员函数的线程安全性

Qt library - thread safety of static members functions

本文关键字:线程 安全性 函数 静态成员 Qt      更新时间:2023-10-16

Qt的文档指出,所有QDateTime函数都是可重入的,用Qt的术语来说,这意味着如果你在另一个线程中创建新的QDateTime对象,你可以安全地使用它。但是以下静态成员是线程安全的吗:QDateTime::currentDateTime和QDateTime::fromTime_t?

辅助线程中的代码:

// 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(); 

我对这篇文章中的以下说法感到困惑http://doc.qt.nokia.com/4.7-snapshot/thread-basics.html:"在Qt文档中,QDateTime::currentDateTime()没有被标记为线程安全的,但是我们可以在这个小例子中使用它,因为我们知道QDateTime::currentDateTime()静态方法没有在任何其他线程中使用。">

如果QDateTime::currentDateTime()不能在辅助线程中使用,那么我们如何以线程安全的方式创建具有当前日期时间的QDateTime对象?

以下是其他类似于上面的静态成员函数,我不知道它们是否可以在线程中安全使用:1) Q定时器::singleShot2) Q字符串::fromUtf83) Q字符串:数字

如果您需要一种线程安全的方式来获取具有当前时间的QDateTime对象,请创建一个保护不安全调用的函数。

QDateTime getCurrentTime()
{
static QMutex mutex;
QMutexLocker locker(&mutex);
return QDateTime::currentDateTime();
}