Qt moveToThread() vs calling new thread when do we use each

前端 未结 2 441
傲寒
傲寒 2020-12-31 23:22

When do we use each of this function calls in a threaded application. given two functions fun1() and fun2() defined in the same class dealing with read/write of data into bu

2条回答
  •  暖寄归人
    2020-12-31 23:35

    Using moveToThread we can change the thread affinity of an object. What the OP asks is how we can run two functions of the same class in different threads.

    Let class A and two functions f1 and f2

    class A
    {
    public:
        void f1();
        void f2(int i); 
        void run(); // shows how we can trigger f1 and f2 in different threads
    }
    

    Qt already provided a class for running functions in different threads and it is called QtConcurrentRun

    The QtConcurrent::run() function runs a function in a separate thread. The return value of the function is made available through the QFuture API.

    The function that is triggered can be either an external function or a member function. So in our case if we wanted from the object itself to start f1 and f2 in different threads we could do the following in run()

    void run()
    {
       // QFuture because f1 is void 
       QFuture future1 = QtConcurrent::run(this, &A::f1);
       int k = 5; // Concurrent run with arguments
       QFuture future2 = QtConcurrent::run(this, &A::f2, k);
    } 
    

    similarly you could execute any public function of any class concurrently, eg

    QImage image = ...;
    QFuture future = QtConcurrent::run(image, &QImage::invertPixels, QImage::InvertRgba);
    
    A a;
    QFuture future1 = QtConcurrent::run(A, &A::f1);
    

    Notice the difference between the two calls:

    QtConcurrent::run() also accepts pointers to member functions. The first argument must be either a const reference or a pointer to an instance of the class. Passing by const reference is useful when calling const member functions; passing by pointer is useful for calling non-const member functions that modify the instance.

    In order to check when a concurrently executed function has finished you should use a QFutureWatcher.

提交回复
热议问题