qt create 将接收消息和处理消息分为两个线程进行,举例通过信号和槽,在槽函数中将接受的消息保存,在启动一个线程处理保存的所有消息
时间: 2024-03-20 10:43:10 浏览: 126
好的,我可以给你一个简单的例子来说明如何在Qt Creator中通过信号与槽机制将接收消息和处理消息分为两个线程。假设你有一个名为`MyThread`的线程类,它的作用是处理保存在`MyThread`对象中的消息队列。在主线程中,你可以这样实现:
```
// MyThread.h
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QObject *parent = nullptr);
void addMessage(const QString &msg);
signals:
void messageAdded();
protected:
void run() override;
private:
QList<QString> m_messages;
QMutex m_mutex;
QWaitCondition m_cond;
};
// MyThread.cpp
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::addMessage(const QString &msg)
{
QMutexLocker locker(&m_mutex);
m_messages.append(msg);
m_cond.wakeOne();
emit messageAdded();
}
void MyThread::run()
{
while (true) {
m_mutex.lock();
while (m_messages.isEmpty()) {
m_cond.wait(&m_mutex);
}
QString msg = m_messages.takeFirst();
m_mutex.unlock();
// 处理消息
// ...
msleep(10); // 模拟消息处理的耗时
}
}
// MainWindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void slotMessageReceived(const QString &msg);
void slotMessageAdded();
private:
Ui::MainWindow *ui;
QThread *m_thread;
MyThread *m_myThread;
};
// MainWindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 创建并启动MyThread对象
m_thread = new QThread(this);
m_myThread = new MyThread();
m_myThread->moveToThread(m_thread);
connect(m_thread, &QThread::started, m_myThread, &MyThread::run);
m_thread->start();
// 连接信号和槽
connect(ui->lineEdit, &QLineEdit::returnPressed, [&]() {
QString msg = ui->lineEdit->text().trimmed();
if (!msg.isEmpty()) {
ui->textEdit->append("Me: " + msg);
m_myThread->addMessage(msg);
ui->lineEdit->clear();
}
});
connect(m_myThread, &MyThread::messageAdded, this, &MainWindow::slotMessageAdded);
}
MainWindow::~MainWindow()
{
delete ui;
// 停止线程并释放资源
m_myThread->quit();
m_myThread->wait();
m_thread->quit();
m_thread->wait();
delete m_myThread;
delete m_thread;
}
void MainWindow::slotMessageReceived(const QString &msg)
{
ui->textEdit->append("AI: " + msg);
}
void MainWindow::slotMessageAdded()
{
m_myThread->blockSignals(true);
while (!m_myThread->m_messages.isEmpty()) {
QString msg = m_myThread->m_messages.takeFirst();
m_myThread->m_mutex.unlock();
slotMessageReceived(msg);
m_myThread->m_mutex.lock();
}
m_myThread->blockSignals(false);
}
```
这个例子中,`MyThread`类继承自`QThread`,它有一个消息队列`m_messages`,并提供了`addMessage()`方法用于向队列中添加消息。`run()`方法则是线程的入口函数,它会循环从队列中取出消息进行处理。在主线程中,当用户输入一条消息时,它会被添加到消息队列中,并发射一个`messageAdded()`信号。`MainWindow`类中有两个槽函数,`slotMessageReceived()`用于处理接收到的消息,`slotMessageAdded()`则是在`messageAdded()`信号被发射时执行,用于将所有已添加到队列中的消息取出来进行处理。注意在`slotMessageAdded()`函数中,为了避免线程冲突,我们使用了`QMutexLocker`和`blockSignals()`方法来保证线程安全。
阅读全文