C++中多线程Singleton的实现

本文介绍了一种使用模板类实现单例模式的方法,并在此基础上展示了如何在多线程环境下确保线程安全。通过实例演示了在C++中如何利用互斥锁(pthread_mutex)来实现单例类的线程同步,确保了多个线程同时访问单例对象时的正确性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. from http://blog.chinaunix.net/xmlrpc.php?r=blog/article&id=4281275&uid=26611383

  2. /**********************************************
  3.  ******* g++ test.cpp -lpthread****************
  4.  * *******************************************/
  5. #include <iostream>
  6. #include <pthread.h>
  7. using namespace std;
  8. template <class T>
  9. class Singleton
  10. {
  11. public:
  12.     Singleton()
  13.     {

  14.     }
  15.     static T* GetInstance()
  16.     {
  17.        if(m_pInstance == NULL)
  18.         {
  19.             pthread_mutex_lock(&mutex);
  20.             if(m_pInstance == NULL)
  21.             {
  22.                 T* temp = new T;
  23.                 m_pInstance = temp;
  24.             }
  25.             pthread_mutex_unlock(&mutex);
  26.         }
  27.         return m_pInstance;
  28.     }
  29. private:
  30.     static T* m_pInstance;
  31.     static pthread_mutex_t mutex;
  32. };

  33. template<class T>
  34. T* Singleton<T>::m_pInstance = NULL;

  35. template<class T>
  36. pthread_mutex_t Singleton<T>::mutex;

  37. class Test:public Singleton<Test>
  38. {
  39. public:
  40.     Test()
  41.     {
  42.         cout<<"Test::Test()."<<endl;
  43.     }
  44. };

  45. void* thread1(void*)
  46. {
  47.     cout<<"In thread1."<<endl;
  48.     Test* test1 = Test::GetInstance();
  49. }

  50. void* thread2(void *)
  51. {
  52.     cout<<"In thread2."<<endl;
  53.     Test* test2 = Test::GetInstance();
  54. }

  55. int main()
  56. {
  57.     const unsigned int thread_num = 20;
  58.     pthread_t thread_id[thread_num];
  59.     for(unsigned int i = 0; i<thread_num;i++)
  60.     {
  61.         pthread_create(&thread_id[i], NULL, thread1, NULL);
  62.     }
  63.     for(unsigned int i = 0; i<thread_num;i++)
  64.     {
  65.         pthread_create(&thread_id[i], NULL, thread2, NULL);
  66.     }
  67.     sleep(1);
  68.     return 0;
  69. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值