[cpp-threads] N2880 and thread_local variables

Beman Dawes bdawes at acm.org
Tue Jun 9 02:34:29 BST 2009


On Mon, Jun 8, 2009 at 6:15 PM, Anthony
Williams<anthony at justsoftwaresolutions.co.uk> wrote:
> 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.
>
> Destroying such an object from a thread other than that in which it was
> created would be an error, as would destroying such objects in any order
> other than the reverse of their construction within a single thread.
>
> Nesting such objects would create a new (blank) context for thread_local
> variables, and the outer context would be restored when the nested object
> was destroyed.

> Alternatively, nested contexts could inherit the set of
> thread_local variables from their parent context, and just destroy any
> newly-set values when the nested context is destroyed.

Without claiming to have done any deep analysis, wouldn't this
alternate behavior be less surprising in that it is very similar to
familiar name viability rules for blocks?

Also, wouldn't this alternate behavior avoid the problem that Peter
pointed out? Presumably the heap would have been set up in the
outermost context, rather than having to be setup and then torn down
as each nested context comes into existence and then dies.

--Beman



More information about the cpp-threads mailing list