Qt 【串口通信】跨线程导致问题及解决办法(跨线程接口的使用)

说明

封装的串口类实例化对象,通过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;
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值