[cpp-threads] N2880 and thread_local variables

Peter Dimov pdimov at mmltd.net
Mon Jun 8 23:30:24 BST 2009


Anthony Williams:
> Hi,
>
> I have been thinking about the issue of thread_local variables with 
> destructors and lifetime that is discussed in N2880, and would like to 
> suggest a possible solution.
>
> My suggestion is this: create a new class thread_local_context which is 
> intended to be used in an RAII manner. Creating an instance creates a new 
> context on the calling thread for thread_local variables to be associated 
> with. When the object is destroyed it destroys all thread_local variables 
> modified on this thread since it was created.

...

> This could then be used to ensure that thread-local variables are cleaned 
> up before waiting threads are notified when using mechanisms other than 
> thread::join to communicate task completion. e.g. 
> std::packaged_task::operator() could be written so as to execute the 
> contained task within the scope of a thread_local_context, but only set 
> the "ready" flag on the future outside the scope, thus ensuring that the 
> thread locals are destroyed before any waiting threads see the future as 
> set.

I agree that this is a good solution to the problem raised in N2880.

As a counterpoint, however, consider this task:

void task()
{
    delete new int;
}

and assume that the implementation of operator new uses thread_local 
variables to maintain a per-thread free list.

Wrapping the task execution in a thread_local_context could slow down this 
task by an order of magnitude (if not several orders of magnitude). 




More information about the cpp-threads mailing list