qt create 将接收消息和处理消息分为两个线程进行,举例通过信号和槽,在槽函数中将接受的消息保存,在启动一个线程处理保存的所有消息,发送的消息是信号传输的,应该如何在Linux下实现
时间: 2024-03-21 13:37:58 浏览: 84
好的,下面是一个基于Linux环境的例子:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <QObject>
#include <QCoreApplication>
class MessageProcessor : public QObject
{
Q_OBJECT
public:
MessageProcessor(QObject *parent = nullptr) : QObject(parent)
{
connect(this, &MessageProcessor::messageReceived, this, &MessageProcessor::onMessageReceived);
}
public slots:
void onMessageReceived(const QString &message)
{
// 处理消息
std::cout << "Received message: " << message.toStdString() << std::endl;
}
signals:
void messageReceived(const QString &message);
};
class TcpClient : public QObject
{
Q_OBJECT
public:
TcpClient(QObject *parent = nullptr) : QObject(parent)
{
connect(&socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
connect(this, &TcpClient::messageReceived, &processor, &MessageProcessor::messageReceived);
}
void connectToServer(const QString &address, int port)
{
socket.connectToHost(address, port);
}
private slots:
void onReadyRead()
{
QString message = QString::fromUtf8(socket.readAll());
emit messageReceived(message);
}
private:
QTcpSocket socket;
MessageProcessor processor;
};
void messageHandler(MessageProcessor &processor, std::condition_variable &cv, std::mutex &mtx, std::queue<QString> &messages)
{
while (true)
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []() { return !messages.empty(); });
QString message = messages.front();
messages.pop();
lock.unlock();
emit processor.messageReceived(message);
}
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
TcpClient tcpClient;
tcpClient.connectToServer("127.0.0.1", 1234);
std::mutex mtx;
std::condition_variable cv;
std::queue<QString> messages;
MessageProcessor processor;
std::thread handlerThread(messageHandler, std::ref(processor), std::ref(cv), std::ref(mtx), std::ref(messages));
QObject::connect(&processor, &MessageProcessor::messageReceived, &app, [](const QString &message) {
std::cout << "Message processed: " << message.toStdString() << std::endl;
});
QObject::connect(&app, &QCoreApplication::aboutToQuit, [&]() {
cv.notify_all();
handlerThread.join();
});
return app.exec();
}
#include "main.moc"
```
这个例子中,我们定义了一个 `MessageProcessor` 类,用于处理接收到的消息。在 `TcpClient` 类中,我们将接收到的消息通过信号传递给 `MessageProcessor` 对象。在 `messageHandler` 函数中,我们将接收到的消息保存到一个消息队列中,并通过条件变量 `cv` 通知消息处理线程。
需要注意的是,在 `main` 函数中,我们需要先启动消息处理线程,再通过 `QObject::connect` 将 `MessageProcessor` 对象的信号与 `QCoreApplication` 的槽函数连接起来。当程序结束时,我们需要通知消息处理线程结束,并等待它结束后再返回。
阅读全文