endless loop with thread

May 5, 2016 at 6:36pm
Hey guys,

I haven't used thread for a long time and would need some help.
I would like to have a endless loop:

1
2
3
4
Update()
{
   while(true){...}
}


I know there is std::thread but i think i don't use it correctly:

1
2
3
std::thread t1(Update);

t1.join -->??


can anybody help me with this simple example :P?
Last edited on May 5, 2016 at 6:36pm
May 5, 2016 at 6:40pm
join will wait for the thread to finish. If the thread is designed to never end, join is going to wait forever.

So under what circumstances do you actually want the thread to end?
May 5, 2016 at 6:46pm
ahm hmm.

the main problem is, that the loop currently consumes too much cpu, because its running for a certain amount of time, maybe even for ever.

Therefore i thought a thread would be a good idea.

But as already meantioned, the loop&thread would run for a certain amount of time or even forever
May 5, 2016 at 6:52pm
If it's meant to run forever anyway, why bother waiting for it? Just let it run while your main thread gets on with whatever else has to be done.
May 5, 2016 at 6:54pm
so this would be enough?

1
2
3
4
5
6
int main()
{
   std::thread t1(Update);

   .......
}


or do i need a second one for other stuff? :P
Last edited on May 5, 2016 at 6:55pm
May 5, 2016 at 8:02pm
The main function will carry on after creating the thread named t1. Do the other stuff in the main function.
May 6, 2016 at 8:30am
ah ok :)
May 6, 2016 at 8:54am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>

void update( std::atomic<bool>& program_is_running, unsigned int update_interval_millisecs )
{
    const auto wait_duration = std::chrono::milliseconds(update_interval_millisecs) ;
    while( program_is_running )
    {
        std::cout << "update stuff\n" << std::flush ;
        std::this_thread::sleep_for(wait_duration) ; 
    }
}

int main()
{
    std::cout << "*** press enter to exit the program gracefully\n\n" ;

    std::atomic<bool> running { true } ;
    const unsigned int update_interval = 50 ; // update after every 50 milliseconds
    std::thread update_thread( update, std::ref(running), update_interval ) ;

    // do other stuff in parallel: simulated below
    std::cin.get() ;

    // exit gracefully
    running = false ;
    update_thread.join() ;
}
Topic archived. No new replies allowed.