[cpp-threads] Update on N2889/N2880/N2901

Peter Dimov pdimov at mmltd.net
Mon Jun 22 20:47:06 BST 2009


Herb Sutter:

> Interjection: This may have merit, but I do want to push back on this in 
> principle. C++ destructors are much more powerful than Java finalizers.

Which is why there is demand for TLS destructors even in Java. :-)

> Actually, this links to something I wondered about: pthreads relies on a 
> hook that can get called with a thread ends. If we had something similar 
> in std::thread, couldn't a library hook into that and accomplish the same 
> thing?

It can, but it's a fairly painful task to do without help from the runtime.

> If not, fallback position: I wonder if it would be enough to say something 
> like "thread_locals can't have nontrivial destructors, except that 
> thread_local std::*_ptr is okay"?

This doesn't affect the destructor question, because a thread_local X and a 
thread_local auto_ptr<X> both invoke ~X. It only affects construction.

> Maybe it's an audience issue. Experienced experts do those things. But on 
> Windows and .NET the guidance to app and library developers is to avoid 
> TLS like the plague in thread pool tasks.

App and library developers should also avoid threads, low-level 
synchronization primitives such as mutexes, atomic variables, globals, 
atexit handlers, and every library function that maintains state or has side 
effects. :-)

>> The straightforward and well-known example that plainly illustrates the
>> above three points is malloc/free with thread-local free lists.
>
> I obviously haven't written one. :-) So this absolutely requires 
> thread_local objects with nontrivial destructors?

You have to return the thread-local free list to the global free pool when a 
thread completes.

> From what little I know of pthreads "destructor" functions, they seem a 
> lot more like Java finalizers than C++ destructors, in particular that 
> they can't access any other TLS data.

They can, and routinely do. It's fairly typical for a TLS destructor to call 
'free', and it's also not atypical for 'free' to return the memory to the 
thread-local free list. POSIX TLS destructors can be invoked more than once, 
until either everything is cleaned up properly or an implementation-specific 
limit of iterations is reached.




More information about the cpp-threads mailing list