Singleton_test.cc revision cd139dc7
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 36cd139dc7SShuo Chenint main() 37cd139dc7SShuo Chen{ 38cd139dc7SShuo Chen muduo::Singleton<Test>::instance().setName("only one"); 39cd139dc7SShuo Chen muduo::Thread t1(threadFunc); 40cd139dc7SShuo Chen t1.start(); 41cd139dc7SShuo Chen t1.join(); 42cd139dc7SShuo Chen printf("tid=%d, %p name=%s\n", 43cd139dc7SShuo Chen muduo::CurrentThread::tid(), 44cd139dc7SShuo Chen &muduo::Singleton<Test>::instance(), 45cd139dc7SShuo Chen muduo::Singleton<Test>::instance().name().c_str()); 46cd139dc7SShuo Chen} 47