










1、模块件采用单例,直接访问对方的接口,接口尽量采用同步设计,所以调用方需要在线程中调用接口
2、模块内部采用invoke访问工作线程的接口
3、invoke封装
///> 异步调用拉姆达 template <typename Func> bool invokeAsync(QObject* obj, Func&& func) { if (!obj) {QLOG_ERROR()<<"invokeAsync failed, obj is null";return false;} return QMetaObject::invokeMethod(obj, std::forward<Func>(func), Qt::QueuedConnection); //直接返回, 异步执行func } ///> 同步调用拉姆达 template <typename Func> bool invokeSync(QObject* obj, Func&& func) { if (!obj) {QLOG_ERROR()<<"invokeSync failed, obj is null";return false;} if (obj->thread() == QThread::currentThread()) { return QMetaObject::invokeMethod(obj, std::forward<Func>(func), Qt::DirectConnection); //直接调用阻塞fun执行完成 } else { return QMetaObject::invokeMethod(obj, std::forward<Func>(func), Qt::BlockingQueuedConnection);//当前线程阻塞, 等待obj线程执行fun完成 } } ///> 异步调用函数指针 template <typename Func, typename... Args> bool invokeAsync(QObject* obj, Func&& func, Args&&...args) { if (!obj) {QLOG_ERROR()<<"invokeAsync failed, obj is null";return false;} return QMetaObject::invokeMethod(obj, func, Qt::QueuedConnection, std::forward<Args>(args)...); } ///> 同步调用函数指针, 带返回值 template <typename Func, typename Ret, typename... Args> bool invokeSync(QObject* obj, Func&& func, Ret& ret, Args&&...args) { if (!obj) {QLOG_ERROR()<<"invokeSync failed, obj is null";return false;} if (obj->thread() == QThread::currentThread()) { return QMetaObject::invokeMethod(obj, func, Qt::DirectConnection, Q_RETURN_ARG(Ret, ret), std::forward<Args>(args)...); } else { return QMetaObject::invokeMethod(obj, func, Qt::BlockingQueuedConnection, Q_RETURN_ARG(Ret, ret), std::forward<Args>(args)...); } } ///> 同步调用函数指针, 不带返回值 template <typename Func, typename... Args> bool invokeSync(QObject* obj, Func&& func, Args&&...args) { if (!obj) {QLOG_ERROR()<<"invokeSync failed, obj is null";return false;} if (obj->thread() == QThread::currentThread()) { return QMetaObject::invokeMethod(obj, func, Qt::DirectConnection, std::forward<Args>(args)...); } else { return QMetaObject::invokeMethod(obj, func, Qt::BlockingQueuedConnection, std::forward<Args>(args)...); } }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。