-
Notifications
You must be signed in to change notification settings - Fork 238
Description
I extended the example in the page 18 as follows. It compiles and runs fine and I can see constructor being called looking at terminal output. But when detach() called, I cant see, any output from the operator() (). I thought operator() will be invoked when my_func is passed my_thread() initialization:
std:thread my_thread(my_func) and detach() allows to run in the background even after main() quits.
But I dont see any output with detach() is called before exising main().
However, if I replace detach() with join(), it works and I get the loop executing as main() blocks until operator()() finish executing.
Can you explain what I did wrong here?
/* This is similar to p13.cpp except it is using example of callable object, in this case
class with () operator defined */
#include <iostream>
#include <thread>
void hello() {
std::cout << "Hello concurrent world.\n";
}
#define DEBUG 1
struct func {
int & i;
func(int & i_) : i(i_){
if (DEBUG == 1) {
std::cout << "func::func() (constructor) entered..." << std::endl;
}
};
void operator() () {
if (DEBUG == 1) {
std::cout << "func::operator() entered..." << std::endl;
}
/*
for (unsigned j=0; j < 1000000 ; ++j) {
if (j % 100000 == 0) {
std::cout << "loop idx j: " << j << ", i: " << i << std::endl;
}
}*/
}
};
void oops() {
int some_local_state = 0;
func my_func(some_local_state);
std::thread my_thread(my_func);
/*Detach() does nothing ?? not sure what happened.. join will print out j-loop.*/
my_thread.detach();
//my_thread.join();
}
int main() {
oops();
}
Ifound similar example on the internet and by the same manner, if I delay the exiting of main() (using chrono API to wait one sec (whcih is a very long time!), followed by detach() now I do see outputs now. So lack of output I mentioned above is main() exits without waiting.