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)
?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.