[Qt Delay Methods] Various methods to implement delay and sleep in Qt


Chapter 1: Basic methods for implementing delay and sleep in Qt

1.1 Use of QThread

QThreadIt is the basic class used for multi-threaded programming in Qt. In this class, there is a very useful method called msleep, which can be used to implement a delay in the current thread.

code example

#include <QThread>

void delayFunction() {
    
    
    QThread::msleep(1000);  // 延迟1000毫秒,即1秒
}

Here QThread::msleep(1000);will cause the current thread to pause for 1 second. This is a blocking delay, meaning it blocks the execution of the current thread.

1.2 Use of QTimer

QTimerIs another class used to implement delayed and scheduled tasks. Unlike QThread, QTimerit is non-blocking.

code example

#include <QTimer>
#include <QObject>

class MyClass : public QObject {
    
    
    Q_OBJECT
public slots:
    void mySlot() {
    
    
        // 执行延迟后的操作
    }
};

// 在某个函数中
MyClass obj;
QTimer::singleShot(1000, &obj, SLOT(mySlot()));  // 1秒后执行mySlot

Here, QTimer::singleShotthe method will trigger the method after 1 second mySlotwithout blocking the current thread.

1.3 Use of QElapsedTimer

QElapsedTimeris a class used to measure elapsed time. It is commonly used for performance analysis.

code example

#include <QElapsedTimer>

QElapsedTimer timer;
timer.start();

// 执行某些操作

qint64 elapsed = timer.elapsed();  // 获取经过的时间(毫秒)

1.4 Use of QDateTime

QDateTimeThe class provides date and time functions and can also be used to implement delays.

code example

#include <QDateTime>
#include <QCoreApplication>

void delay(int msec) {
    
    
    QDateTime dieTime = QDateTime::currentDateTime().addMSecs(msec);
    while (QDateTime::currentDateTime() < dieTime) {
    
    
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }
}

Here, we use QDateTime::currentDateTime().addMSecs(msec)to get the delayed time, and then use a loop to wait.

As Bjarne Stroustrup said in "The C++ Programming Language": "C++ is a multi-paradigm programming language that supports different programming styles." [1] In Qt, these different delay and sleep methods are multi-paradigm programming ideas manifestation.

Chapter 2: Differences between Qt5 and Qt6

2.1 Differences in QThread

In Qt5 and Qt6, QThreadthe basic functions are roughly the same. However, Qt6 introduces some new APIs and improvements that make multi-threaded programming more convenient.

code example

Usage in Qt5 QThread:

QThread thread;
Worker worker;

worker.moveToThread(&thread);
connect(&thread, SIGNAL(started()), &worker, SLOT(doWork()));
thread.start();

Usage in Qt6 QThread:

QThread thread;
Worker worker;

worker.moveToThread(&thread);
connect(&thread, &QThread::started, &worker, &Worker::doWork);  // 使用新的信号和槽语法
thread.start();

In Qt6, the way signals and slots are connected has been improved, making the code clearer.

2.2 Differences in QTimer

QTimerSome minor improvements were made in Qt6, but the basic usage remains the same.

code example

The usage in Qt5 and Qt6 QTimeris basically the same:

QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(update()));
timer.start(1000);

2.3 Differences between QElapsedTimer and QDateTime

There is no significant difference between these two classes in Qt5 and Qt6. They are both used for time measurement and delay, and the API remains basically the same.

2.4 Summary

Qt6 has some improvements and optimizations over Qt5, but most of the classes and methods used for delay and hibernation remain the same. This means that migration from Qt5 to Qt6 is generally smooth and does not require extensive code changes.

As a celebrity once said: "Time is the most valuable of all wealth." [2] In software development, precise control of time is crucial, and Qt achieves this by providing a variety of methods.

Chapter 3: Low-level implementation under Linux

3.1 The underlying implementation of QThread under Linux

In Linux systems, QThreadthe underlying implementation is based on POSIX threads (also known as Pthreads). QThread::msleep()The method is actually a wrapper around the nanosleepor usleepsystem call.

underlying source code

In some Linux distributions, this functionality is implemented in the function qthread_unix.cppin the file QThread::msleep.

void QThread::msleep(unsigned long msecs)
{
    
    
    struct timespec ts = {
    
     msecs / 1000, (msecs % 1000) * 1000 * 1000 };
    nanosleep(&ts, NULL);
}

3.2 QTimer在Linux下的底层实现

QTimer 在Linux下通常使用时间戳或者Linux的定时器机制(例如 timerfd)进行实现。

底层源码

在Linux系统中,QTimer 的实现通常位于 qtimer_linux.cpp 文件中。

// 示例代码,展示timerfd的使用
int timerFd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);

3.3 QElapsedTimer和QDateTime在Linux下的底层实现

QElapsedTimer 在Linux下通常使用 clock_gettime 函数。而 QDateTime 则通常使用 gettimeofdaytime 函数。

底层源码

在Linux系统中,这些功能的实现通常位于 qelapsedtimer_unix.cppqdatetime_unix.cpp 文件中。

// QElapsedTimer 使用 clock_gettime
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);

// QDateTime 使用 gettimeofday
struct timeval tv;
gettimeofday(&tv, NULL);

第四章:方法对比与使用建议

4.1 QThread vs QTimer vs QElapsedTimer vs QDateTime

这几种方法各有优缺点,选择哪一种取决于具体的应用场景。

  • QThread:适用于需要长时间运行或需要并行处理的任务。
  • QTimer:适用于需要定时触发某个事件或函数的场景。
  • QElapsedTimer:适用于需要精确测量时间间隔的场景。
  • QDateTime:适用于需要处理日期和时间的场景。

4.2 何时使用哪种方法

  • 需要并行处理任务:使用QThread。
  • 需要定时触发事件:使用QTimer。
  • 需要精确测量时间:使用QElapsedTimer。
  • 需要处理日期和时间:使用QDateTime。

4.3 在不同版本和操作系统下的注意事项

  • 在Qt5和Qt6之间迁移时,注意API的微小变化。
  • 在Linux系统下,了解底层实现可以帮助你更有效地使用这些方法。

4.4 总结与建议

选择合适的方法不仅可以提高代码的效率,还可以使代码更易于维护。正如一位名人曾说:“选择是一种能力,也是一种责任。”[4]

在编程中,合理地选择延迟和休眠的方法,就像在生活中做出明智的选择一样,都是至关重要的。

结语

在我们的编程学习之旅中,理解是我们迈向更高层次的重要一步。然而,掌握新技能、新理念,始终需要时间和坚持。从心理学的角度看,学习往往伴随着不断的试错和调整,这就像是我们的大脑在逐渐优化其解决问题的“算法”。

这就是为什么当我们遇到错误,我们应该将其视为学习和进步的机会,而不仅仅是困扰。通过理解和解决这些问题,我们不仅可以修复当前的代码,更可以提升我们的编程能力,防止在未来的项目中犯相同的错误。

我鼓励大家积极参与进来,不断提升自己的编程技术。无论你是初学者还是有经验的开发者,我希望我的博客能对你的学习之路有所帮助。如果你觉得这篇文章有用,不妨点击收藏,或者留下你的评论分享你的见解和经验,也欢迎你对我博客的内容提出建议和问题。每一次的点赞、评论、分享和关注都是对我的最大支持,也是对我持续分享和创作的动力。


阅读我的CSDN主页,解锁更多精彩内容:泡沫的CSDN主页
在这里插入图片描述

Guess you like

Origin blog.csdn.net/qq_21438461/article/details/132916934