function multiple thread static

1
2
3
4
5
int& fun()
{
	static int i{ 100 };
        return  i;
}

if multiple thread call fun simultaneously, 'i' will be initialized more than one time?
Last edited on
> static int i{ 100 };

The initializer 100 is an integral constant expression; there is no dynamic initialisation here.

Here, there is dynamic initialisation
1
2
3
4
5
int& fun()
{
	static int i = std::rand() ;
        return  i;
}

and the rules for dynamic initialisation are:
Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration.

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. [Footnote: The implementation must not introduce any deadlock around execution of the initializer]

If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
[Example:
1
2
3
4
int foo(int i) {
    static int s = foo(2*i); // recursive call - undefined
    return i+1;
}

—end example ]
thanks!
Topic archived. No new replies allowed.