Are funtions of class is thread-safe when using QObject::moveToThread?

  • @class MyClass {
    int result;

    void add(int i)
    result += i; // Let's say it's long calculation ;)

    int result()
    return result;

    for (int i = 0; i < 3; i++)

    // Let's say "i" is very large data, when adding in the loop like this.
    // Is it wait ultil i has been sent to myClass or it's just send and go to next loop?
    // In general it will wait for sure i has been sent before go to the next loop but
    // because myClass is thread now I'm not sure how it work.
    for (int i = 0; i < 3; i++)

    // Is it safe to do this while "add" funtion is calculating
    int answer;
    for (int i = 0; i < 3; i++)
    answer = myClass[i].result();

  • Moderators


    No they are not thread-safe unless you make them thread safe.

    See "Synchronizing Threads": for details.

  • movethread takes care of your signals/slots and events. Not executing with other methods. So they are not thread safe. You need make thread safe using any of the available synchronization methods.

  • OK, thanks very much.

    How about this?
    @for (int i = 0; i < 3; i++)

    Is there anyway to do this in pararell?

  • How about looking at QtConcurrent ? It may help.

  • OK, thanks again ;)

  • Yea you definitely want to look in the docs on this one.

    There are a few ways to make that run concurrently, but you really need to understand multithreading or you will open yourself up to tons of crashes and problems. And they will be very complicated to solve without the synchronization understanding.

    If you have more questions once you have a better understanding of threading feel free to post them and I'd be happy to help you out.

    And if you really just need the code to do it I can give that to you as well, but I highly recommend learning it and doing it for yourself. Threading can be very complicated and fully understanding it will save you a lot of problems in the future. :)

  • Thanks so much for your advice.
    One of my problems is I'm don't know C++ good enought,
    so it's little slow to sync with Qt lol.

    I tried with wxWidgets before and I'm dead with threading.
    It's never simple when go with threading. T T

  • Yea threading is one of the more difficult concepts in programming.

    Being weak with C++ is going to make it very tough to use Qt well. It's doable but it's going to be frustrating for you. I wouldn't let that stop you though. It's entirely possible to learn c++ and qt at the same time. It might just be a bit slower than if you were already good with c++.

    Qt is way better than wxWidgets so you made a good switch. :) In my opinion they aren't even in the same class.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.