qt多线程获取某个信号发送时间
时间: 2023-08-06 10:09:32 浏览: 110
QT多线程编程
在Qt中,可以使用`QTime`类来获取当前时间,而在多线程中,可以使用`QMutex`类来确保线程安全。具体实现可以参考以下示例代码:
```c++
#include <QApplication>
#include <QObject>
#include <QThread>
#include <QTime>
#include <QMutex>
class Worker : public QObject
{
Q_OBJECT
signals:
void signalTime(QTime time);
public slots:
void doWork()
{
QMutex mutex;
while (true) {
mutex.lock();
QTime time = QTime::currentTime();
emit signalTime(time);
mutex.unlock();
QThread::msleep(1000);
}
}
};
class Receiver : public QObject
{
Q_OBJECT
public slots:
void slotTime(QTime time)
{
qDebug() << "Current time: " << time.toString("hh:mm:ss.zzz");
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Worker worker;
Receiver receiver;
QThread thread;
worker.moveToThread(&thread);
QObject::connect(&worker, &Worker::signalTime, &receiver, &Receiver::slotTime);
QObject::connect(&thread, &QThread::started, &worker, &Worker::doWork);
thread.start();
return a.exec();
}
#include "main.moc"
```
在上述代码中,`Worker`类中的`doWork()`函数不断地获取当前时间并发送`signalTime`信号,而`Receiver`类中的`slotTime()`槽函数则接收并打印该信号的发送时间。同时,由于多线程涉及到共享资源的访问,因此使用`QMutex`类确保线程安全。
阅读全文