static & thread_local variables¶static & non-local variables¶static and non-local variables with dynamic initialization is thread-safenamespace bcc1 {
const auto& get_table() {
static const vector<type_index> result = {typeid(int), typeid(long), typeid(short)};
return result;
}
} // namespace bcc1
namespace bcc2 {
const auto& get_table() {
static const auto result = [] {
vector<type_index> r{typeid(int), typeid(long), typeid(short)};
sort(begin(r), end(r));
return r;
}();
return result;
}
} // namespace bcc2
thread_local variables¶thread_local implies static storage durationthread_local variables with dynamic initialization are initialized at the start of every thread startthread_local variables are initialized on first execution in a given threadthread_local imposes about a 15% performance penalty (at least on Apple platforms) compared to accessing a static variablenamespace {
auto& context() {
thread_local vector<string> result;
return result;
}
} // namespace bcc3
thread_local variable doesn't require synchronizationnamespace {
void do_stuff() { cout << "context: " << context().back() << endl; }
} // namespace
context().push_back("selecting");
do_stuff();
context().push_back("painting");
do_stuff();
context().pop_back();
do_stuff();
context().pop_back();
constexpr variablesthread_local variables impact the startup of every threadstatic local variableconst to ensure thread safetythread-local local variables can be a useful tool for establishing auxiliary scope informationstatic which does not have thead-safe initializationpthread_once(), boost::call_once() or similar (simplify)pthread_getspecific(), boost::thread_specific_ptr() or similar (simplify)static with dynamic initialization which could be constexpr