简体   繁体   English

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

[英]Qt library - thread safety of static members functions

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. Qt的文档指出,所有QDateTime函数都是可重入的,以Qt术语来说,这意味着,如果您在另一个线程中创建QDateTime的新对象,则可以安全地使用它。 But are the following static members thread safe: QDateTime::currentDateTime and QDateTime::fromTime_t? 但是以下静态成员线程安全吗:QDateTime :: currentDateTime和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." 我对本文中的以下声明感到困惑,即http://doc.qt.nokia.com/4.7-snapshot/thread-basics.html :“ QDateTime :: currentDateTime()在Qt中未标记为线程安全的文档,但是在这个小例子中我们可以避免使用它,因为我们知道QDateTime :: currentDateTime()静态方法未在任何其他线程中使用。”

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? 如果不能在辅助线程中使用QDateTime :: currentDateTime(),那么我们如何以线程安全的方式使用当前日期时间创建QDateTime对象呢?

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 以下是其他类似上面的静态成员函数,我不知道它们是否可以在线程中安全使用:1)QTimer :: singleShot 2)QString :: fromUtf8 3)QString:number

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对象,请创建一个保护不安全调用的函数。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM