22#include  < iostream> 
33#include  < sstream> 
44#include  < thread> 
5+ #include  < future> 
56
67namespace  StaticUsage  {
78
89 struct  CountedObject  {
9-  int  data;
10- 
11-  static  CountedObject CreateNew ()
10+  static  CountedObject GetInstance ()
1211 {
13-  std::cout << " called from thread: " std::this_thread::get_id () << std::endl << std::flush;
14-  CountedObject::_id++; //  increment totat creation count
15-  return  CountedObject ();
16-  }
17- 
18-  static  unsigned  int  TotalCreationCount () {
19-  return  CountedObject::_id;
12+  //  With C++11 static member initializations are thread safe
13+  static  CountedObject instance;
14+  return  instance;
2015 }
21- 
2216 private: 
23-  CountedObject () = default ;
24-  static  unsigned  int  _id;
17+  CountedObject ()
18+  {
19+  std::cout << " CountedObject() thread: " std::this_thread::get_id () << " \n " 
20+  }
2521 };
26-  // static
27-  unsigned  int  CountedObject::_id = 0 ;
2822}
2923
30- ELEMENT_CODE (StaticUsageExample) {
24+ ELEMENT_CODE (StaticUsageExample) 
25+ {
3126 using  namespace  StaticUsage ; 
32-  std::thread t1 ([]() {
33-  for  (size_t  i = 0 ; i < 10 ; i++)
34-  {
35-  CountedObject::CreateNew ();
36-  }
37-  });
38-  for  (size_t  i = 0 ; i < 10 ; i++)
39-  {
40-  CountedObject::CreateNew ();
41-  }
27+  std::promise<void > wait_flag;
28+  auto  watier = wait_flag.get_future ();
29+ 
30+  std::thread t1 ([] (auto  wait_flag) {
31+  wait_flag.set_value ();
32+  CountedObject::GetInstance ();
33+  }, std::move (wait_flag));
34+  watier.wait ();
35+  CountedObject::GetInstance ();
4236 t1.join ();
43-  printf (" Total creation count: %d" CountedObject::TotalCreationCount ());
4437}
0 commit comments