转载请注明: https://blog.csdn.net/Stephen___Qin/article/details/115583694

  1. #include <thread>
  2. #include <iostream>
  3. using namespace std;
  4. class Singleton
  5. {
  6. private:
  7. Singleton()
  8. {
  9. }
  10. static Singleton * m_singleton;//C++类中不可以定义自己类的对象,但是可以定义自己类的指针和引用.
  11. public:
  12. static Singleton * getInstance();
  13. };
  14. Singleton * Singleton::m_singleton = nullptr;
  15. Singleton * Singleton::getInstance()
  16. {
  17. if(m_singleton == nullptr)
  18. m_singleton = new Singleton();
  19. return m_singleton;
  20. }
  21. void ThreadFunc()
  22. {
  23. Singleton *s = Singleton::getInstance();
  24. std::cout << "s:" << s << std::endl;
  25. }
  26. int main()
  27. {
  28. thread t1(ThreadFunc);
  29. t1.join();
  30. thread t2(ThreadFunc);
  31. t2.join();
  32. thread t3(ThreadFunc);
  33. t3.join();
  34. return 0;
  35. }

注意:
1.构造函数要定义为private,这样就无法创建对象,保证只能通过类名来访问单例.
2.static变量需要在类外初始化.为什么呢?因为静态变量不属于某个对象,而是属于类,如果放在类内初始化,则变成了这个对象的了,这就和之前的假设矛盾了

  1. #include <thread>
  2. #include <iostream>
  3. #include <mutex>
  4. using namespace std;
  5. static std::once_flag of;
  6. class Singleton
  7. {
  8. private:
  9. Singleton()
  10. {
  11. }
  12. static Singleton * m_singleton;
  13. public:
  14. static Singleton * getInstance();
  15. };
  16. Singleton * Singleton::m_singleton = nullptr;
  17. Singleton * Singleton::getInstance()
  18. {
  19. std::call_once(of, []()
  20. {
  21. m_singleton = new Singleton();
  22. }
  23. );
  24. return m_singleton;
  25. }
  26. void ThreadFunc()
  27. {
  28. Singleton *s = Singleton::getInstance();
  29. std::cout << "s:" << s << std::endl;
  30. }
  31. int main()
  32. {
  33. thread t1(ThreadFunc);
  34. t1.join();
  35. thread t2(ThreadFunc);
  36. t2.join();
  37. thread t3(ThreadFunc);
  38. t3.join();
  39. return 0;
  40. }

注意:
1.call_once和once_flag的头文件是<mutex>
2.once_flag定义为static或者全局对象,否则不同线程间不可见,则无法起到作用.

参考文章:
https://zhuanlan.zhihu.com/p/71900518

版权声明:本文为Stephen-Qin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/Stephen-Qin/p/14642192.html