3

Normally, when main() exits, all threads are killed. pthread_exit(3) says

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

Is there an equivalent C++11 API call? Something like std::this_thread::exit(0)?

Tavian Barnes
  • 12,477
  • 4
  • 45
  • 118
  • May be you should rather looking for [something like this](http://stackoverflow.com/questions/3095566/linux-daemonize) (not portable, I know). – πάντα ῥεῖ Jun 29 '16 at 18:51
  • Why would you want your threads to continue running after the main thread exits? Could you just wait for them to complete first? – Dylon Jun 29 '16 at 19:06
  • 1
    @Dylon To be honest I'm hoping the standard says this isn't allowed. Makes something I'm working on simpler. – Tavian Barnes Jun 29 '16 at 19:33
  • If the real question is if you can safely have something that is destroyed when you exit `main` that might be accessed by a running thread, the answer is no. Something destroyed after you might join that thread. – David Schwartz Jun 29 '16 at 20:09

2 Answers2

0

Historically, the main() function has been special - it represents the lifetime of the application. C++11 does not change this.

When the main function returns, the program cleans up and terminates. That's hard-coded into the C runtime.

Anything that will prevent main from retuning normally will work (but there is no portable way to terminate a thread).

A workaround in your case might be just to block the main thread forever, or re-use it to do some monitoring/housekeeping.

rustyx
  • 80,671
  • 25
  • 200
  • 267
0

Page 1121 of the Working Draft, Standard for Programming Language C++ from 2012-01-16 seems to state that once the main thread exits, its detached threads will be cleaned up as well (unless I'm misinterpreting it):

void detach();

Requires: joinable() is true.

Effects: The thread represented by *this continues execution without the calling thread blocking. When detach() returns, *this no longer represents the possibly continuing thread of execution. When the thread previously represented by *this ends execution, the implementation shall release any owned resources.

Postcondition: get_id() == id().

Throws: system_error when an exception is required (30.2.2).

Error conditions:

— no_such_process — if the thread is not valid.

— invalid_argument — if the thread is not joinable.

Community
  • 1
  • 1
Dylon
  • 1,730
  • 15
  • 14
  • 4
    They're not "cleaned up" they just stop existing. If they access any global objects between the main thread returning from main and the process actually exiting (e.g. while global destructors are running) you risk undefined behaviour. The wording you quote about _"the implementation shall release any owned resources"_ is talking about when the detached thread exits, but returning from `main` doesn't cause that to happen, the detached threads are still running. – Jonathan Wakely Jun 29 '16 at 20:53