Singleton_test.cc revision 8ce0c3b5
1cd139dc7SShuo Chen#include "../Singleton.h" 2cd139dc7SShuo Chen#include "../Thread.h" 3cd139dc7SShuo Chen 4cd139dc7SShuo Chen#include <boost/noncopyable.hpp> 5cd139dc7SShuo Chen#include <stdio.h> 6cd139dc7SShuo Chen 7cd139dc7SShuo Chenclass Test : boost::noncopyable 8cd139dc7SShuo Chen{ 9cd139dc7SShuo Chen public: 10cd139dc7SShuo Chen Test() 11cd139dc7SShuo Chen { 12cd139dc7SShuo Chen printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); 13cd139dc7SShuo Chen } 14cd139dc7SShuo Chen 15cd139dc7SShuo Chen ~Test() 16cd139dc7SShuo Chen { 17cd139dc7SShuo Chen printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); 18cd139dc7SShuo Chen } 19cd139dc7SShuo Chen 20cd139dc7SShuo Chen const std::string& name() const { return name_; } 21cd139dc7SShuo Chen void setName(const std::string& n) { name_ = n; } 22cd139dc7SShuo Chen 23cd139dc7SShuo Chen private: 24cd139dc7SShuo Chen std::string name_; 25cd139dc7SShuo Chen}; 26cd139dc7SShuo Chen 27cd139dc7SShuo Chenvoid threadFunc() 28cd139dc7SShuo Chen{ 29cd139dc7SShuo Chen printf("tid=%d, %p name=%s\n", 30cd139dc7SShuo Chen muduo::CurrentThread::tid(), 31cd139dc7SShuo Chen &muduo::Singleton<Test>::instance(), 32cd139dc7SShuo Chen muduo::Singleton<Test>::instance().name().c_str()); 33cd139dc7SShuo Chen muduo::Singleton<Test>::instance().setName("only one, changed"); 34cd139dc7SShuo Chen} 35cd139dc7SShuo Chen 368ce0c3b5SShuo Chentemplate<unsigned N> 378ce0c3b5SShuo Chenclass Destruct 388ce0c3b5SShuo Chen{ 398ce0c3b5SShuo Chen public: 408ce0c3b5SShuo Chen Destruct() 418ce0c3b5SShuo Chen { 428ce0c3b5SShuo Chen printf("construct %d\n", N); 438ce0c3b5SShuo Chen more(); 448ce0c3b5SShuo Chen } 458ce0c3b5SShuo Chen 468ce0c3b5SShuo Chen ~Destruct() 478ce0c3b5SShuo Chen { 488ce0c3b5SShuo Chen printf("destruct %d\n", N); 498ce0c3b5SShuo Chen } 508ce0c3b5SShuo Chen 518ce0c3b5SShuo Chen void more() 528ce0c3b5SShuo Chen { 538ce0c3b5SShuo Chen muduo::Singleton<Destruct<N-1> >::instance(); 548ce0c3b5SShuo Chen } 558ce0c3b5SShuo Chen}; 568ce0c3b5SShuo Chen 578ce0c3b5SShuo Chentemplate<> 588ce0c3b5SShuo Chenvoid Destruct<0>::more() 598ce0c3b5SShuo Chen{ 608ce0c3b5SShuo Chen} 618ce0c3b5SShuo Chen 62cd139dc7SShuo Chenint main() 63cd139dc7SShuo Chen{ 64cd139dc7SShuo Chen muduo::Singleton<Test>::instance().setName("only one"); 65cd139dc7SShuo Chen muduo::Thread t1(threadFunc); 66cd139dc7SShuo Chen t1.start(); 67cd139dc7SShuo Chen t1.join(); 68cd139dc7SShuo Chen printf("tid=%d, %p name=%s\n", 69cd139dc7SShuo Chen muduo::CurrentThread::tid(), 70cd139dc7SShuo Chen &muduo::Singleton<Test>::instance(), 71cd139dc7SShuo Chen muduo::Singleton<Test>::instance().name().c_str()); 728ce0c3b5SShuo Chen 738ce0c3b5SShuo Chen muduo::Singleton<Destruct<500> >::instance(); 74cd139dc7SShuo Chen} 75