QThread - Changing a cut condition



  • I have a working thread running a loop with a boolean cut condition. The thread starts fine and runs the loop. When I try to stop it, by calling a method which changes this cut condition to false, it doesn't work. I mean, the value doesn't change. (cut = false; and cut keeps true!)
    The only way to change the cut condition value is inside the loop.
    The cut condition is a member of this QThread object, and it's not locked.

    Here a boceto:
    @
    void doLoop()
    {
    while(keepGoing)
    {
    doSomething();
    }
    }

    void putCutConditionToFalse()
    {
    keepGoing = false; // It DOESN'T work!
    }
    @

    How can change this value?.


  • Moderators

    Check the obvious first - are these two really running in different threads (eg. print "QThread::currentThreadId()":http://qt-project.org/doc/qt-5/qthread.html#currentThreadId
    Maybe you've got the threading code wrong.



  • Both methods are part of the same object.
    QThread::currentThreadId() returns always the same id, no matter from where I call it.
    What I'm doing wrong?. I create my QThread as a member of my QMainWindow, and when I push a button, the QThread object starts a new thread.


  • Lifetime Qt Champion

    Hi,

    IIRC, the loop might be optimized by the compiler in such a way that it ends up being an infinite loop and keepGoing doesn't have any effect.

    For this kind of scenario, I use a QAtomicInt that you ref before starting and unref when you want to stop.


  • Moderators

    Sounds like your code executes in the main thread.
    How do you start a thread? Did you use moveToThread or reimplemented run?



  • Perhaps try defining keepGoing as volatile
    @
    volatile bool keepGoing;
    @


  • Moderators

    It doesn't matter how he defines keepGoing, atomic, volatile or other if all the code runs in the same thread. Besides - volatile doesn't mean thread-safe.



  • [quote author="Chris Kawa" date="1402386153"]It doesn't matter how he defines keepGoing, atomic, volatile or other if all the code runs in the same thread. Besides - volatile doesn't mean thread-safe.[/quote]

    Yes that is all true. But given that the loop is in a different thread, and it only reads keepGoing while only one other thread will try to write keepGoing then it is generally safe.

    If it is indeed threaded an all of the above assumptions are not valid one needs either atomic variables or locks (mutex, semaphores, etc.)



  • ninio, I think it would be better if you provide the whole code so we can see how you're actually starting the thread, using the boolean member and calling these methods.


Log in to reply
 

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