how to deal with one class(object) with several steps function which need to run in multiple threads.



  • Hi all,

    Hope I can make it clearly and someone can help me, thanks in advance.

    Now I have a class such as:
    class A: QObject{
    Q_OBJECT
    ...
    private:
    Object data1; //queue
    Object data2; //queue

    void step1(); //create data1
    void step2(); //use data1, create data2
    void step3(); //use data2

    signals:
    ...
    public slots:
    ...
    }

    What I want to do is create a A object and run those 3 steps to make a whole task, and those 3 steps need to be run in its own thread, so need 3 threads at all.

    I found that only QThread::create() (Qt 5.10+) can make function run in a thread, but I don't know how to do it in this case.

    Can anyone give me some suggestions?



  • I'm not sure I completely understand, but can you create a public function in A that calls your three step functions, and do something like this:

        a = new A();
        thread = new QThread;
        a->moveToThread(thread);
        thread->start();
    

    You'd define a slot in the A c'tor to invoke the public function mentioned above.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Sounds like you should take a look at the Qt state machine framework to model your situation.



  • Check out QRunnable and QThreadpool.

    Setup a threadpool with 3 threads (or more) and make runnables with your tasks that need to be processed.



  • Many thanks to all of you, @mzimmers @SGaist @MrShawn , I will try things you suggested ASAP.


Log in to reply