How to create a looping thread?
Apr 6, 2016 at 6:18am UTC
I was wondering if it was possible to create a temporary thread that would always loop and execute until the classes destructor is called? So far I have this which is pretty crappy in that I can't do anything else with that thread running. And well I want it to be able to start the thread and then proceed to do other things.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void func_thread() {
cout << "FUNC_THREAD\n" ;
}
class looping_thread {
private :
std::thread actions;
public :
looping_thread() {
actions = std::thread(func_thread);
loop();
}
void loop() {
std::this_thread::sleep_for(chrono::seconds(1));
if (actions.joinable()) {
actions.join();
}
else {
actions = std::thread(func_thread);
}
start();
}
void start() {
loop();
}
~looping_thread() {
actions.detach();
}
};
int main() {
looping_thread* go = new looping_thread; //INFINITE RECURSION/THREAD
for (int i = 0; i < 15; i++) {
std::cout << "MAIN" << '\n' ; //WANT THIS TO EXECUTE WITH THE THREAD EXECUTING IN THE BACKGROUND AS WELL.
std::this_thread::sleep_for(chrono::milliseconds(250));
}
delete go;
char response;
cin >> response;
return 0;
}
Apr 6, 2016 at 4:53pm UTC
~bump
Apr 6, 2016 at 6:00pm UTC
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 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <thread>
#include <functional>
#include <atomic>
#include <chrono>
struct active_object
{
template < typename FN > active_object( FN fn ) : thread( [this ,fn] { while (alive) fn() ; } ) {}
~active_object() { alive = false ; thread.join() ; }
active_object( const active_object& ) = delete ;
active_object( active_object&& ) = delete ;
active_object& operator = ( active_object ) = delete ;
std::atomic<bool > alive {true } ;
std::thread thread ;
};
int main()
{
{
std::cout << "press enter to destroy object\n" ;
using namespace std::literals ;
active_object obj( [] { std::cout << "hello\n" ; std::this_thread::sleep_for( 200ms ) ; } ) ;
for ( int i = 0; i < 15; i++ ) {
std::cout << "main\n" ;
std::this_thread::sleep_for( 300ms );
}
std::cin.get() ;
}
std::cout << "done\n" ;
}
Last edited on Apr 6, 2016 at 6:15pm UTC
Apr 6, 2016 at 7:02pm UTC
Note that this is brutally modern C++. It's like a whole new language :)
Apr 6, 2016 at 7:47pm UTC
@Moschops Yeah I can tell lol. I need to get good in a lot of things.
@JLBorges Dude your a beast at c++ how did you learn all of those tricks? Are you like an all time professional programmer or something?
Apr 7, 2016 at 2:47am UTC
> how did you learn all of those tricks?
A little bit at a time, over a long time.
Topic archived. No new replies allowed.