[英]Qt library - thread safety of static members functions
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 :“ QDateTime :: currentDateTime()在Qt中未標記為線程安全的文檔,但是在這個小例子中我們可以避免使用它,因為我們知道QDateTime :: currentDateTime()靜態方法未在任何其他線程中使用。”
如果不能在輔助線程中使用QDateTime :: currentDateTime(),那么我們如何以線程安全的方式使用當前日期時間創建QDateTime對象呢?
以下是其他類似上面的靜態成員函數,我不知道它們是否可以在線程中安全使用:1)QTimer :: singleShot 2)QString :: fromUtf8 3)QString:number
如果您需要一種線程安全的方法來獲取當前時間的QDateTime對象,請創建一個保護不安全調用的函數。
QDateTime getCurrentTime()
{
static QMutex mutex;
QMutexLocker locker(&mutex);
return QDateTime::currentDateTime();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.