Are major global initializers defined for single-threaded processing?

For example, the constructor node::node() in the following fragment of accessing global variables node::count and ::tail without any multi-threaded guards. Does the C ++ standard guarantee that the output will always be a permutation 0 1 2 (regardless of order)?

 #include <stdio.h> struct node *tail; struct node { static int count; int index; node *prev; node() { index = count++; prev = tail; tail = this; } }; int node::count; node one, two[2]; int main(int argc, char *argv[]) { for(node *p = tail; p; p = p->prev) printf("%d\n", p->index); return 0; } 

I am looking for an answer based on a (applicable) standard, and not on a specific execution or compiler. There are a number of related questions on SO, but it’s not entirely clear how they are directly applied to this specific and rather basic case ( Is the initialization of a static C ++ member variable stream safe? Is the local static variable initialization thread safe in C ++ 11? etc.).

+6
source share
1 answer

Initialization of global variables is guaranteed single-threaded if the program itself does not start the thread (for example, in the constructor of some global variable); as soon as this happens, the implementation will be allowed to parallelize to some extent the remaining initializations.

[basic.start.init] / 2 ... Variables with ordered initialization defined in one translation unit must be initialized in the order of their definitions in the translation block. If the program starts the thread (30.3), the subsequent initialization of the variable does not depend on the initialization of the variable defined in another translation unit. Otherwise, the initialization of the variable is indefinitely sequenced relative to the initialization of the variable defined in another translation unit. If a program starts a thread, subsequent unordered initialization of the variable is independent of any other dynamic initialization. Otherwise, the unordered initialization of a variable is indefinitely ordered relative to every other dynamic initialization. [Note. This definition allows you to simultaneously initialize a sequence of ordered variables with another sequence. -end note]

An "indefinite sequence" is the part that guarantees single-threaded execution. By definition, the concept of sequencing {before, after, indefinitely} makes sense in only one thread:

[intro.execution] / 13 The sequence before is the relationship between evaluations performed by a single thread ...

+5
source

All Articles