thread_safe_init

Controls the addition of extra code in the binary to ensure that multiple threads cannot enter a static local initialization at the same time.

Syntax
#pragma thread_safe_init on | off | reset
  
Remarks

A C++ program that uses multiple threads and static local initializations introduces the possibility of contention over which thread initializes static local variable first. When the pragma is on , the compiler inserts calls to mutex functions around each static local initialization to avoid this problem. The C++ runtime library provides these mutex functions.

Listing 1. Static local initialization example
int func(void) {
  // There may be synchronization problems if this function is 
  // called by multiple threads.
  static int countdown = 20;

  return countdown--;
}
Note: This pragma requires runtime library functions which may not be implemented on all platforms, due to the possible need for operating system support.

Example thread_safe_init shows another example.

Listing 2. Example thread_safe_init
#pragma thread_safe_init on

void thread_heavy_func()
{
  // Multiple threads can now safely call this function:
  // the static local variable will be constructed only once.
  static std::string localstring = thread_unsafe_func();
}
Note: When an exception is thrown from a static local initializer, the initializer is retried by the next client that enters the scope of the local.

This pragma does not correspond to any panel setting. By default, this pragma is off .

Related information
access_errors
always_inline
arg_dep_lookup
ARM_conform
ARM_scoping
array_new_delete
auto_inline
bool
cplusplus
cpp1x
cpp_extensions
debuginline
def_inherited
defer_codegen
defer_defarg_parsing
direct_destruction
direct_to_som
dont_inline
ecplusplus
exceptions
inline_bottom_up
inline_bottom_up_once
inline_depth
inline_max_auto_size
inline_max_size
inline_max_total_size
internal
iso_templates
new_mangler
no_conststringconv
no_static_dtors
nosyminline
old_friend_lookup
old_pods
old_vtable
opt_classresults
parse_func_templ
parse_mfunc_templ
RTTI
suppress_init_code
template_depth
warn_hidevirtual
warn_no_explicit_virtual
warn_no_typename
warn_notinlined
warn_structclass
wchar_type