说明
封装的串口类实例化对象,通过moveToThread移动到子线程中运行,想要在任务线程中使用这个串口对象的收发接口,可以使用QMetaObject::invokeMethod这个接口来实现。
代码实现
main函数
实现serialportiml实例化,通过impl->moveToThread(thread1);转移到子线程中,
然后将serialportiml实例化对象impl传入任务对象worker 中。
QThread *thread1 =new QThread;
QSharedPointer<serialportiml> impl = serialportiml::CreateSerialPortIml(cfg);
QObject::connect(thread1, &QThread::started, impl.get(), &serialportiml::Init);
QObject::connect(impl.get(), &serialportiml::destroyed, thread1, &QThread::quit);
QObject::connect(thread1, &QThread::finished, thread1, &QThread::deleteLater);
impl->moveToThread(thread1);
QThread *thread2 =new QThread;
QSharedPointer<worker> worker = worker::CreateWorker(opticalpower,impl,cfg);
QObject::connect(worker.get(), &opticalpower::destroyed, thread2, &QThread::quit);
QObject::connect(thread2, &QThread::finished, thread2, &QThread::deleteLater);
worker->moveToThread(thread2);
worker对象函数
WritePWM接口通过QMetaObject::invokeMethod调用m_sptrSerialportiml中WritePWM函数,这样函数执行在thread1 线程中。
bool worker::WritePWM(quint16 nLeftPWM,quint16 nRightPWM)
{
bool isok=false;
QMetaObject::invokeMethod(m_sptrSerialportiml.get(), "WritePWM", Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, isok),
Q_ARG(quint16 , nLeftPWM),
Q_ARG(quint16 , nRightPWM));
return isok;
}