Qt-QtConcurrent


QtConcurrent
High-level APIs that make it possible to write multi-threaded programs without using low-level threading primitives

本次简单的使用Qt的Concurrent的线程相关,对其理解就是个开辟一个独立的线程,任务型的线程,结束任务即结束。

QtConcurrent本质是个命名空间,通过QtConcurrent::run(T (*functionPointer),args)即可将一个函数放到线程中执行。如下:

    namespace QtConcurrent {
    // 一般使用
    template <typename T>
    QFuture<T> run(T (*functionPointer)())
    {
        return (new StoredFunctorCall0<T, T (*)()>(functionPointer))->start();
    }
    
    // 使用类的成员函数
    template <typename T, typename Class>
    QFuture<T> run(QThreadPool *pool, const Class &object, T (Class::*fn)())
    {
        return (new typename SelectStoredMemberFunctionCall0<T, Class>::type(fn, object))->start(pool);
    }
    }

eg:

    void test(){}
    void testEx(int index){}
    class Test{
    public:
        void classNoConst(QString ret){
            qDebug() << ret;
        }
        void classWithConst(QString ret) const{
            qDebug() << ret;
        }
    };
    ...
    // testPart
    {
        // use normal
        QtConcurrent::run(test);
        
        // use normal with arg
        QtConcurrent::run(testEx, 10);
        
        //  常量成员函数一般传递 常量引用 (const reference),而非常量成员函数一般传递 指针 (pointer)
        Test t_test;
        // use class fun no const
        QtConcurrent::run(&t_test,&Test::classNoConst, "no const");
        // use class fun const
        QtConcurrent::run(t_test,&Test::classWithConst, "const");
        
        // use lambda
        QString str = "str";
        QFuture<QString> ret = QtConcurrent::run([&](QString other){
                return QString("%1_%2").arg(str).arg(other);
        },QString("over"));
    }


 

猜你喜欢

转载自blog.csdn.net/qq_39175540/article/details/85984523
QT