Consider the following example (lock guards on cout
omitted for simplicity).
#include <future>
#include <iostream>
#include <thread>
using namespace std;
struct C
{
C() { cout << "C constructor
";}
~C() { cout << "C destructor
";}
};
thread_local C foo;
int main()
{
int select;
cin >> select;
future<void> f[10];
for ( int i = 0;i < 10; ++i)
f[i] = async( launch::async,[&](){ if (select) foo; } );
return 0;
}
On both clang and gcc, this program outputs nothing if the user writes '0', while it prints Constructor
/Destructor
10 times if the user inputs a non zero number.
Additionally clang complains about an obvious non used expression result.
Since a thread_local
storage life-time is supposed to span the entire thread's life, I expected the foo
variable to be initialized in every thread regardless of the user input.
I might want to have a thread-local
variable for the sole purpose of having a side-effect in the constructor, does the standard mandates that a thread_local
object is initialized on its first use?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…