C++ Thread consumes all CPUs



  • Hi friends.

    I have a function. In my function there is a c++ thread & a Qtimer. By c++ thread I receive ARP Reply packets & by QTimer I send ARP Request packets.

    The simplified structure:

    @
    int foo()
    {
    ... some codes ...

    QTimer::singleShot(1000, this, SLOT(beginSending()));
    
    std::thread tCapture(Capture);
    tCapture.join();
    
    return 0;
    

    }
    @

    @
    void Capture()
    {
    while ( ! finishCapturing )
    {
    do sth
    }
    }

    @

    In the tCapture thread I have a while loop that consumes all CPUs & the Qtimer does not work!
    I use .join() because I want to wait for the thread to finish.
    when I ser the 'finishCapturing ' flag in Qtimer slot, the thread will be finished.

    The above codes dont work correctly, because the c++ thread consumes all CPUs!

    what is the problem?

    Thanks a lot.
    Ya Ali.


  • Moderators

    [quote]
    @
    while ( ! finishCapturing )
    {
    do sth
    }
    @
    [/quote]This loop will do sth as fast as it can go -- that's why it's consuming 100% CPU. You need to tell it to sleep() to stop it from consuming all your CPU time.



  • Hello dear JKSH,

    I had used sleep() but did not work!



  • Why don't you use the better QThread? Or the other thread classes in Qt? There is ample documentation off it and works great without you have to worry about threading etc.
    "Threading!":http://qt-project.org/doc/qt-5/qtconcurrent-index.html



  • Hello dear Jeroentje@home,

    Yes but as I said in my first post, I don't want the foo function finish before completing Capture thread & the slot.



  • If the new thread is spawned from the same thread that QTimer's message queue is processed in, it won't work. The call to join() blocks that thread indefinitely, so the "timer alarm" event is never processed and your thread is never stopped. You should always only join() a thread after signalling termination.

    edit: if QTimer's message queue is processed in another thread, it won't work either, as then you have an indirect connection to your timeout slot, which won't be processed.


  • Moderators

    [quote author="mmoll" date="1405594535"]If the new thread is spawned from the same thread that QTimer's message queue is processed in, it won't work. The call to join() blocks that thread indefinitely, so the "timer alarm" event is never processed and your thread is never stopped.[/quote]Good catch!


Log in to reply
 

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