Files
BloomPatched/src/Services/DateTimeService.hpp

54 lines
1.8 KiB
C++
Raw Normal View History

2021-04-04 21:04:12 +01:00
#pragma once
#include <mutex>
#include <QDateTime>
#include <QDate>
2021-04-04 21:04:12 +01:00
namespace Services
2021-04-04 21:04:12 +01:00
{
/**
* Some (maybe all) QDateTime static functions are not thread-safe and thus can result in data races.
* This trivial service class wraps some of these functions and employs a mutex to prevent data races.
2021-04-04 21:04:12 +01:00
*/
class DateTimeService
2021-04-04 21:04:12 +01:00
{
public:
/**
* The QDateTime::currentDateTime() static function is not thread-safe. This may be caused by the
* underlying interfacing with the system clock.
*
* @return
*/
static QDateTime currentDateTime() {
const auto lock = std::unique_lock(DateTimeService::systemClockMutex);
2021-04-04 21:04:12 +01:00
return QDateTime::currentDateTime();
}
/**
* This function calls QDateTime::currentDateTime(). See comment for DateTime::currentDateTime().
*
* @return
*/
static QDate currentDate() {
const auto lock = std::unique_lock(DateTimeService::systemClockMutex);
return QDateTime::currentDateTime().date();
}
2021-04-04 21:04:12 +01:00
/**
* The QDateTime::timeZoneAbbreviation() is a non-static member function but it may still interface with the
* system clock. This can result in race conditions when called simultaneously to QDateTime::currentDateTime(),
* and so any calls to it must require possession of the mutex.
*
* @param dateTime
* @return
*/
static QString getTimeZoneAbbreviation(const QDateTime& dateTime) {
const auto lock = std::unique_lock(DateTimeService::systemClockMutex);
2021-04-04 21:04:12 +01:00
return dateTime.timeZoneAbbreviation();
}
private:
2022-07-16 19:12:45 +01:00
static inline std::mutex systemClockMutex;
2021-04-04 21:04:12 +01:00
};
}