Qt通信架构

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)...);
    }
}

 

posted @ 2026-08-25 19:45  朱小勇  阅读(10)  评论(0)    收藏  举报