Introduction
Since C++11, static local variable has been made sure to be thread safe by C++11 standard. In singleton for example, static keyword is often used to extend the life time of local variable to the end of program and initialized only once. What’s interesting is the behavior of static local variable in multi-thread environment.
Example
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
int init() {
cout << "init here" << endl;
return 5;
}
int get_singleton() {
static int singleton = init();
return singleton;
}
int main() {
vector<thread> ts(10);
for (int i = 0; i < 10; i++) {
ts[i] = thread([]() {
int a = get_singleton();
});
}
for (int i =