Linux c++: Will blocked threads prevent app process terminating after returning from main function?

Viewed 39

This problem is duplicate, but I am still confused about how os will resolve child threads after returning from main function.

Most pepole said that os will invoke exit_group() or exit() to terminate all child threads. However, I found blocked threads will prevent process terminating.Reading up the documention of linux man page, I didn't find the special works for blocked threads.

#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>

using namespace std;

mutex m;
condition_variable cv;

int main() {
  auto t = thread([]() {
    unique_lock<mutex> lock(m);
    cv.wait(lock);
  });
  t.detach();
  sleep(1);
  cout << "hello" << endl;
  return 0;
}

Running above code will print "hello" and then always stuck in blocking.

If simulate the behaviors os to do, directly invoke _exit(2) (be equivalent to exit_group()) in main function, process will terminate normally.

#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>

using namespace std;

mutex m;
condition_variable cv;

int main() {
  auto t = thread([]() {
    unique_lock<mutex> lock(m);
    cv.wait(lock);
  });
  t.detach();
  sleep(1);
  cout << "hello" << endl;
  exit(0);
  return 0;
}

If use exit() instead of _exit(2), process will be stuck after printing "hello".

So what exactly did os do after returning for main funcion? Will blocked threads prevent process terminating?

The following code will work normally.

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>

using namespace std;

mutex m;
condition_variable cv;

int main() {
  auto t = thread([]() {
    unique_lock<mutex> lock(m);
    cv.wait(lock);
  });
  t.detach();
  auto t2 = thread([](){
      unique_lock<mutex> lock(m);
      cv.wait_for(lock,chrono::seconds(2));
      cv.notify_all();
  });
  t2.detach();
  sleep(1);
  cout << "hello" << endl;
  return 0;
}
0 Answers
Related