C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Make std::thread not joinable after thread function ends.

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 21 Jun 2023 23:00:17 -0700
On Wednesday, 21 June 2023 22:28:21 PDT Arthur O'Dwyer via Std-Proposals
wrote:
> (1) could that list somehow be exploited to find out if the thread was
> ready, without an ABI break at all? E.g. initialize the list with one dummy
> element, and then have `.is_ready()` just check whether the list is empty
> right now.

No. libstdc++'s std::thread has exactly one member, which is a
std::thread::id. That type has exactly one member, which is a
std::thread::native_handle_type.

So you can get exactly as much as what the lower layer gives you, no more.

> (2) could `notify_all_at_thread_exit` be used somehow to emulate/polyfill
> this feature? but I suppose we already know how to emulate it by wrapping
> the whole thread in a lambda...

Yes. Just register a condition variable to be notified at thread exit, then use
the condvar's wait_for(0) to test if it has been signalled.

> (3) ...except that it wouldn't surprise me if there's a way to run
> arbitrarily large amounts of code at thread exit!

Of course. I was not kidding when I said it could take a century between the
closing brace of the run function and the thread terminating. It's not that I
think it will take a century in any reasonable scenario, it's that you have to
design your code as if it could.

> Either through some very
> clever abuse of the standard facilities listed above (which I think have
> been designed with the intent of never blocking), or through some pthreads
> facility. In which case the approach in (2) would actually be insufficient,
> because you could finish the thread's actual work, return from the lambda,
> set your "ready" flag, get ready to exit the thread for real... and then
> suddenly have an arbitrarily large amount of code to run before the thread
> has actually exited (so during that arbitrarily long time your "ready" flag
> is lying).

Example: non-trivially destructible thread_local.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-06-22 06:00:19