关于QDateTime的线程安全性问题

本例测试了QDateTime中几个函数的线程安全性

  • QDateTime::currentDateTime()
  • QDateTime().toString(format)
  • QDateTime::fromString

编译器使用mingw

测试结果

函数 Qt5.12 Qt6.74
QDateTime::currentDateTime() 未崩溃 未崩溃
DateTime().toString(format) 崩溃 未崩溃
QDateTime::fromString 崩溃 未崩溃

实验代码

测试函数

#include <QCoreApplication>
#include <QDateTime>
#include <QRandomGenerator>
#include <QThreadPool>
#include <QTimer>
#include <QDebug>

const QDateTime commonDate = QDateTime::currentDateTime();
const QString format = "yyyyMMdd hh:mm:ss.zzz";
const QString timeString = "20250709 12:34:56.789";
std::atomic_bool stop = false;

// 测试函数
void fun1(){
    while(!stop){
        QDateTime date = QDateTime::currentDateTime();
    }
}
void fun2(){
    while(!stop){
        auto string = commonDate.toString(format);
    }
}
void fun3(){
    while(!stop){
        auto date = QDateTime::fromString(timeString,format);
    }
}

// ======== 适配Qt5的线程池,封装成QRunnable ========
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
class Fun1:public QRunnable{
public:
    void run(){
        fun1();
    };
};
class Fun2:public QRunnable{
public:
    void run(){
        fun2();
    };
};
class Fun3:public QRunnable{
public:
    void run(){
        fun3();
    };
};
#endif

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    const int threadCount = QThread::idealThreadCount();

    QThreadPool pool;
    pool.setMaxThreadCount(threadCount);
    for(int i = 0;i<threadCount;i++){
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
        // pool.start(new Fun1); // QDateTime::currentDateTime ok
        // pool.start(new Fun2);    // QDateTime().toString       crashed
        pool.start(new Fun3); // QDateTime::fromString      crashed
#else
        pool.start(fun1); // QDateTime::currentDateTime ok
        pool.start(fun2); // QDateTime().toString       ok
        pool.start(fun3); // QDateTime::fromString      ok
#endif
    }
    QTimer::singleShot(60*5*1000,[&pool](){
        stop = true;
        pool.waitForDone();
        qApp->quit();
    });
    return a.exec();
}
posted @ 2025-07-09 11:32  料峭春风吹酒醒  阅读(34)  评论(0)    收藏  举报