gpt4 book ai didi

c++ - QThreads之间如何发送数据?

转载 作者:行者123 更新时间:2023-11-28 06:11:54 26 4
gpt4 key购买 nike

我在一个线程中有一个事件,需要在另一个线程中调用处理函数。通常我使用函数 connect(),但如果有两个线程,我会出错:

QObject::connect: Cannot queue arguments of type 'QVector<unsigned char>'
(Make sure 'QVector<unsigned char>' is registered using qRegisterMetaType().)

我尝试使用 qRegisterMetaType(),但不清楚我应该如何以及在何处声明它。我编写了代码示例,它只是从 thead1 调用线程 0 中的执行。我没有包括我使用 qRegisterMetaType() 的尝试,因为它们都失败了 =)

线程0.h:

#ifndef THREAD0_H
#define THREAD0_H

#include <QThread>
#include <QVector>

class thread0 : public QThread
{
Q_OBJECT
public:
thread0();
~thread0();

protected:
void run() Q_DECL_OVERRIDE;

public slots:
void printBuff(QVector<unsigned char> vec);
};

#endif // THREAD0_H

线程1.h:

#ifndef THREAD1_H
#define THREAD1_H

#include <QThread>
#include <QVector>

class thread1 : public QThread
{
Q_OBJECT
public:
thread1();
~thread1();

protected:
void run() Q_DECL_OVERRIDE;

signals:
void sendToPrint(QVector<unsigned char> vec);
};

#endif // THREAD1_H

主要.cpp:

#include <QCoreApplication>
#include "thread0.h"
#include "thread1.h"
#include <QObject>
#include <QMetaType>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

thread0 *th0 = new thread0();
thread1 *th1 = new thread1();

QObject::connect(th1, &thread1::sendToPrint, th0, &thread0::printBuff);

th0->start();
th1->start();

return a.exec();
}

和thread1.cpp:

#include "thread1.h"

thread1::thread1()
{

}

thread1::~thread1()
{

}

void thread1::run()
{
QVector<unsigned char> vec = {0, 1, 2, 3};
emit sendToPrint(vec);
}

附言如果我使用直接连接代码工作。

QObject::connect(th1, &thread1::sendToPrint, th0, &thread0::printBuff, Qt::DirectConnection);

最佳答案

在你的 main() 中添加这个

qRegisterMetaType<QVector<unsigned char> >("QVector<unsigned char>");

在线程之间,Qt 使用队列连接。这种机制要求通过信号将每个类型作为参数传递给 Qt 元对象系统已知的插槽。大多数 Qt 类型已经注册,但不是模板类型,因为每个模板特化需要一个 qRegisterMetaType

如果您使用直接连接,您的代码可能看起来有效,但 printBuff 将在 th1 中运行,而不是 th0。而事实上,th0 线程什么都不做。如果 printBuff 设计为仅在线程 0 中运行,这可能会导致程序崩溃,因为线程安全问题。

关于c++ - QThreads之间如何发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com