Verification on thread security of the static class object constructor in c ++ 11, static Constructor
In c ++ 11, static class objects are thread-safe during the initialization of constructors. With this feature, we can easily implement Singleton classes by ourselves, for more information about how to implement thread-safe Singleton classes, see c ++: a class c ++ Singleton class that implements thread-safe. The following is an example of verification:
1. Listing 1: staticSafe. h
1 # include <iostream> 2 # include <thread> 3 using namespace std; 4 class Cnum 5 {6 public: 7 Cnum () 8 {9 std :: cout <"construct start" <std: endl; 10 std: this_thread: sleep_for (std: chrono: seconds (5 )); // sleep in the constructor 5s11 num ++; 12 std: cout <"construct stop" <std: endl; 13} 14 void Test () 15 {16 std: cout <"id:" <std: this_thread: get_id () <", num =" <num <std :: endl; 17 std: this_thread: sleep_for (std: chrono: seconds (1); 18} 19 static int num; 20 };
2. Listing 2: main. cpp
1 int Cnum: num = 0; // initialize static member 2 void func (void * argv) 3 {4 int I = * (int *) argv; 5 std :: cout <I <std: endl; // when each thread is started, print the thread serial number 6 static Cnum a; // thread security during initialization of internal static member variables, only one thread can execute initialization, and other threads will block 7. test (); 8} 9 void main () 10 {11 for (int I = 0; I <10; I ++) // start 10 threads, simulate concurrent access 12 {13 std: thread t1 (func, (void *) & I); 14 t1.detach (); 15} 16 system ("pause "); // pause for 17}
3. Running result
From the results, we can see that: 1) after "construct stop" is printed, other threads will execute the Test function one after another. 2) num printed by all threads is 1. The above phenomenon indicates that when a thread executes the constructor of the static Class Object, other threads that want to access the static class object are blocked.