0
void thread_fn() {
  while (1) {
    this_thread::sleep_for(chrono::seconds(1));
    std::cout << "Inside thread function\n";
  }
}

int main()
{
    cout << getpid() << "My PID" << endl;
    std::thread t1(thread_fn);
    t1.detach();
    return 0;
}

QUESTION 1 -What will happen to detached thread, after main exits? After some reading i figured out OS will try to do the cleanup, once thread exits. But here i am not exitting at all. Will it keep on running for ever? (till system reboots..)

QUESTION 2 -How can i kill it when process which invoked the thread has already been killed?

QUESTION 3 -Is there a need to kill it (assume thread is doing some heavy task)?

Vishwadeep Singh
  • 1,043
  • 1
  • 13
  • 38
  • no. scenario is infinite thread is not explained. – Vishwadeep Singh Jun 30 '17 at 06:47
  • The second answer says "It continues to run" - you need to actively kill it in your code, if you detach it. – Mats Petersson Jun 30 '17 at 06:51
  • My idea to re-ask was, because after running the code, i couldn't see in the process table and no where else. Hence do i need to forcefully restart my machine to get rid of it. I think i had learnt the concept the hard way. – Vishwadeep Singh Jun 30 '17 at 06:55
  • Threads continue to run after `main()` has exited, but it does not mean that the threads will continue to run after the process has stopped or has been killed. There are things that happen between the end of `main()` and the end of the process, and that is precisely what is discussed in the other question. But in the end the OS will kill the threads for you when it ends the process. – Benjamin T Jun 30 '17 at 08:33
  • Thanks @BenjaminT I was thinking as a programmer, and i think for multi threading i need to take care os basics also. :) – Vishwadeep Singh Jul 07 '17 at 05:53

0 Answers0