Is passing a std::future
to a detached instance of std::thread
a safe operation? I know that underneath, the std::future
has state in a shared_ptr which it shares with a std::promise
. Here is an example.
int main()
{
std::promise<void> p;
std::thread( [f = p.get_future()]() {
if ( f.wait_for( std::chrono::seconds( 2 ) ) == std::future_status::ready )
{
return;
}
std::terminate();
} ).detach();
// wait for some operation
p.set_value();
}
There is a potential error case in the above code where the lambda is executed after the main thread exits. Does the shared state remain after the main thread exits?
Once a thread has been detached, it can't be joined with pthread_join(3) or be made joinable again. A new thread can be created in a detached state using pthread_attr_setdetachstate(3) to set the detached attribute of the attr argument of pthread_create(3).
Yes, it is ok and safe in you code. But it does not have any sense. main function will utilize CPU and a thread function will get less CPU time.
If a thread is created as detached, it can never be joined. The final draft of the POSIX standard specifies that threads should be created as joinable. To explicitly create a thread as joinable or detached, the attr argument in the pthread_create() routine is used.
detach() is mainly useful when you have a task that has to be done in background, but you don't care about its execution. This is usually a case for some libraries. They may silently create a background worker thread and detach it so you won't even notice it.
[basic.start.term]/6 If there is a use of a standard library object or function not permitted within signal handlers (21.10) that does not happen before (4.7) completion of destruction of objects with static storage duration and execution of
std::atexit
registered functions (21.5), the program has undefined behavior.
Per [basic.start.main]/5, returning from main
has the effect of calling std::exit
, which does destroy objects with static storage duration and execute std::atexit
registered functions. Therefore, I believe your example exhibits undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With