我试图使用QtConcurrent并发运行一个函数,但我遇到了其中一个参数的问题。
作为前身,假设我有以下类和“接口”:
class DataMessage : public QObject {
Q_OBJECT
// ... fields and methods
};
class ITimeStampInfo {
public:
virtual QDateTime timestamp() const = 0;
};
Q_DECLARE_INTERFACE(ITimeStampInfo, "My.TimeStampInfo/1.0")
class IDataLengthInfo {
public:
virtual int dataLength() const = 0;
};
Q_DECLARE_INTERFACE(IDataLengthInfo, "My.IDataLengthInfo/1.0")
class DataMessage1 : public DataMessage, public ITimeStampInfo {
Q_OBJECT
Q_INTERFACES(ITimeStampInfo)
// other fields, etc
QDateTime timestamp() const;
};
class DataMessage2 : public DataMessage, public IDataLengthInfo {
Q_OBJECT
Q_INTERFACES(IDataLengthInfo)
// other fields
int dataLength() const;
};和一个名为processDataMessages的类函数
void MyClass::processDataMessages(DataMessage *msg) {
// Previous to this function being called, concrete `DataMessage`
// instances are created and passed by pointer into this function
// Determine the data in the message
IDataLengthInfo *dl = qobject_cast<IDataLengthInfo*>(msg);
if (dl) {
qDebug() << "Got a message with IDataLengthInfo";
}
ITimeStampInfo *ts = qobject_cast<ITimeStampInfo*>(msg);
if (ts) {
qDebug() << "Got a message with ITimeStampInfo";
}
// etc
}此processDataMessages在slot中调用。在正常操作期间,此函数可以正常工作,并且只要指针正确,qDebug()语句就会按预期执行-例如,在调试器中检查指针类型会产生DataMessage1类型
我现在想异步运行这个函数,因为可能会有一些工作要做。如果我尝试从插槽中使用QtConcurrent::run执行这个函数,如下所示:
void MyClass::dataReceived(DataMessage *msg) {
// this->processDataMessages(msg);
QtConcurrent::run(this, &MyClass::processDataMessages, msg);
}现在,当我在processDataMessages函数的第一个qobject_cast行中断时,我可以看到msg指针的类型是DataMessage,而不是DataMessage1或DataMessage2类型。
在QtConcurrent::run的操作过程中丢失了一些东西,我可能遗漏了一些愚蠢的东西。
发布于 2017-09-21 23:33:05
好的,事实证明,下面的代码是有效的:
QFuture<void> f = QtConcurrent::run(this, &MyClass::processDataMessages, msg);
// Wait for the function to finish
f.waitForFinished();看起来与原始文件没有什么不同,但返回值中的某些内容可能是维护状态??
https://stackoverflow.com/questions/46347496
复制相似问题