#include #include #include #include #include using namespace std; //--------------------------------------------------------------- // This method mimics the thread doing some actual work. // It is extremely rare that calling sleep() is the right // thing to do -- extremely rare. You should basically never // do it, as there's some better way in code that actually // does something. //--------------------------------------------------------------- void sleep_spin(int delay) { for (int i = 0; i < 4; i++) { cout << " sleep_spin(" << delay << ") sleeping..." << endl; sleep(delay); cout << " sleep_spin(" << delay << ") done sleeping." << endl; } } //--------------------------------------------------------------- // New threads start executing here. They terminate when // they return from this method. //--------------------------------------------------------------- void thread_start(int delay) { cout << "[child thread] I'm alive!" << endl; cout << "[child thread] calling sleep_spin(" << delay << ")" << endl; sleep_spin(delay); cout << "[child thread] done." << endl; } //--------------------------------------------------------------- // The (single) main thread starts executing here. //--------------------------------------------------------------- int main(int argc, char **argv) { // Create a child thread, passing it 1 as its argument. cout << "[parent thread] about to create thread..." << endl; thread tr = thread(thread_start, 1); // wait for that thread to finish cout << "[parent thread] joining child thread" << endl; tr.join(); cout << "[parent thread] joined child thread" << endl; // do it again, but this time detach from thread cout << "[parent thread] creating second thread" << endl; thread tr2 = thread(thread_start, 60); tr2.detach(); cout << "[parent thread] done." << endl; return EXIT_SUCCESS; }