https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108299
Bug ID: 108299
Summary: toplevel thread_local variables are not initialized if
not referenced and initialized at wrong moment when
referenced
Product: gcc
Version: 12.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: agriff at tin dot it
Target Milestone: ---
The standard mandates that thread_local variables at top level must be
initialized in case anything in the compilation unit is referred to. There is a
specific note on the fact that they must be initialized even if they're not
used in the program.
Also they must be initialized at thread start or before anything from the
compilation unit is accessed by the thread.
This code however shows that g++ doesn't follow this rule
#include <stdio.h>
thread_local int flag = ([](){
printf("HERE!\n");
return 1;
})();
int main() {
printf("Hello, world.\n");
return 0;
}
In this version the thread local initialization is skipped.
Mover if after the printf the statement
flag;
is added then the initialization is performed, but AFTER the "Hello, world"
message (another violation of the standard).
Trying on godbolt I saw the problem is present even in trunk and in clang
(works as expected in MSVC).
The problems are present both on the main implicit thread and with threads
started explicitly with std::thread.