C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fix bad thread_local codegen (using an attribute?)

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 21 Jan 2026 20:36:52 -0800
On Wednesday, 21 January 2026 19:14:36 Pacific Standard Time levoplusplusio---
via Std-Proposals wrote:
> On Wed, Jan 21, 2026 at 04:48:26PM -0800, Thiago Macieira via Std-Proposals
wrote:
> I'm not sure how many developers would say that after looking at the
> assembly.

It isn't doing anything wrong. It is doing exactly what is required to support
initialising on-demand, without knowing how to initialise. And it has an
escape route in case the initialiser symbol isn't defined.

> > GCC is missing some optimisation opportunities there, by emitting the
> > check
> > for the initialisation routine's presence repeatedly. Switch to Clang and
> > you'll see that it generates much better code. Not that it's perfect: I
> > don't understand why it emitted a call to flush(), because the condition
> > should have been obvious to be impossible. Maybe it's thinking that the
> > object could change between function calls?
>
> I'm not sure how many developers would say that after looking at the
> assembly.

Those who can read assembly.

> > > I was thinking about allowing something like `extern MyClass myObj{i,
> > > promise, to, init, like, _this_};` However, this may break some
> > > behavior.
> >
> > What behaviour might it break? Because it compiles.
>
> I'm not sure how many developers would say that after looking at the
> assembly.

Those who have tried what I asked and noticed that it improved the code
generation.

> > It is even better if you do initialise the array:
> > https://godbolt.org/z/xMP1qYqYE
>
> I'm surpised godbolt showed the assembly. If you do that in real code you'll
> get a redefinition error.

A linker error? Then solve it by making it inline.

Or solve by not accessing the variable everywhere, but add an accessor
function that can see the initialisation of the variable. Preferably, make the
variable static.

> > There is no problem.
>
> Unless you care about performance, which is why I measured and noticed this
> years ago. I was talking to this with a friend (and ran into a situation
> where __thread won't compile), I figure this may not get fixed unless asked

And I do, and there are solutions for this. I don't think you've explored
enough of them to declare that there is something to be solved.

__thread won't compile *because* it is only allowed for objects without
constructors, where zero-initialisation is an acceptable construction. If this
is what you want, then why not do exactly that?

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Data Center - Platform & Sys. Eng.

Received on 2026-01-22 04:37:08