在Qt中,你可以使用QThread类和信号槽机制来实现类似的功能。下面是一个示例代码:
#include <QCoreApplication>
#include <QObject>
#include <QDebug>
#include <hiredis/hiredis.h>
class RedisSubscriber : public QObject
{
Q_OBJECT
public:
explicit RedisSubscriber(QObject* parent = nullptr)
: QObject(parent) {}
signals:
void messageReceived(const QString& channel, const QString& data);
public slots:
void run()
{
// 在这里执行订阅逻辑
redisContext* context = redisConnect("localhost", 6379);
if (context != nullptr && context->err == 0)
{
redisReply* reply = static_cast<redisReply*>(redisCommand(context, "SUBSCRIBE channel_name"));
if (reply != nullptr && reply->type == REDIS_REPLY_ARRAY && reply->elements >= 3)
{
while (true)
{
redisReply* message = nullptr;
if (redisGetReply(context, reinterpret_cast<void**>(&message)) == REDIS_OK)
{
if (message != nullptr && message->type == REDIS_REPLY_ARRAY && message->elements >= 3)
{
QString channel = message->element[1]->str;
QString data = message->element[2]->str;
// 发送信号将数据传递给接收者
emit messageReceived(channel, data);
}
freeReplyObject(message);
}
}
}
freeReplyObject(reply);
}
redisFree(context);
}
};
class MessageHandler : public QObject
{
Q_OBJECT
public slots:
void handleMessage(const QString& channel, const QString& data)
{
// 在这里处理接收到的消息
qDebug() << "Received message on channel" << channel << ":" << data;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
RedisSubscriber subscriber;
MessageHandler handler;
QObject::connect(&subscriber, &RedisSubscriber::messageReceived, &handler, &MessageHandler::handleMessage);
QThread thread;
subscriber.moveToThread(&thread);
QObject::connect(&thread, &QThread::started, &subscriber, &RedisSubscriber::run);
thread.start();
return a.exec();
}
#include "main.moc"
在上述代码中,我们使用QObject
子类和信号槽机制来实现消息传递。RedisSubscriber类作为订阅者,在其run()函数中执行循环等待数据的逻辑,并通过信号messageReceived()
发送接收到的消息给接收者。MessageHandler类是一个简单的示例,负责处理接收到的消息。
注意,我们需要将RedisSubscriber对象移到新线程,并确保该对象在该线程内执行。另外,在主线程中使用信号槽连接将RedisSubscriber发出的消息与MessageHandler的处理函数关联起来。
希望这可以帮助你在Qt中实现类似于C++原生线程detach方式的功能。
内容由零声教学AI助手提供,问题来源于学员提问