Important: Please read the Qt Code of Conduct -

May need help with GUI + Multi Threading

  • Hello,
    what i want to do:
    GUI has a Class XYZ with a QVector, that Class creates ℕ threads with another instance of that same class, all have a pointer to their "creator" class and they are running an algorithm to search for a solution. if one of the threads finds the solution, it gives to the "creator" class a QVector with the solution in it and then the GUI should update.

    maybe better to understand workflow:

    1. User fills a QVector with numbers
    2. clicks "start calculate" ( important: gui shouldnt freeze )
    3. "XYZ creator" creates ℕ threads and starts them to search for the solution
    4. if one of the threads finds the solution, it will give it back the solution as QVector to the creator
    5. all other threads stop running cuz solution was found
    6. GUI reads from the creator and updates and displays the solution

    i already looked to the example of the mandelbrot but it didnt really helped me :/
    actually its just the GUI without multithreading and its freezing while it searches ....
    im reading the threading stuff but im struggling to find the right way ...

    does someone has good advices for me?

    would be very happy about good advices to start this :)

    greetings :)

  • @MaKoZer
    Keep all your computation threads separate from the main GUI thread. A thread which finds a solution can emit a signal telling the creator-thread it's been found, and that can terminate the other threads.

    I think all the sub-threads can read the creator-thread's QVector OK (no updating or going out of scope). Not sure how you pass a QVector with the answer back from a thread. QSharedPointer can be used if needed.

  • Lifetime Qt Champion


    If you pass around your creator object, then you have to properly protect your access to it. The easiest is to leverage Qt's signal and slot mechanism like shown in the mandelbrot example. As for stoping the other thread, depending on your algorithm, you should have an exit point you check from time to time because "terminating" threads is not the best way to stop them.

  • @JonB
    yeah but how do i do this if the GUI is the start point and the GUI starts everything else? x.X

    but ill keep working on this

  • Lifetime Qt Champion

    How do you do what ?

  • Ok if someone finds this thread with the same problem:

    Your Class needs to inherit from QThread.
    Class has private:
    QVector<Class*> workers;
    QVector<QFuture<void>> qfs;

    Method to start MT in your class:

    void mt_search(Class &worker) {

    Method to start:

    bool Class::runCalc() {
      for (quint8 i = 0; i < num_threads; i++) {
            workers.push_back(new Class());
            qfs.push_back(QtConcurrent::run(mt_search, *workers[i]));

    works pretty fine now :)

Log in to reply