ThreadLocalSingleton_test.cc revision cd139dc7
1cd139dc7SShuo Chen#include "../ThreadLocalSingleton.h" 2cd139dc7SShuo Chen#include "../Thread.h" 3cd139dc7SShuo Chen 4cd139dc7SShuo Chen#include <boost/bind.hpp> 5cd139dc7SShuo Chen#include <boost/noncopyable.hpp> 6cd139dc7SShuo Chen#include <stdio.h> 7cd139dc7SShuo Chen 8cd139dc7SShuo Chenclass Test : boost::noncopyable 9cd139dc7SShuo Chen{ 10cd139dc7SShuo Chen public: 11cd139dc7SShuo Chen Test() 12cd139dc7SShuo Chen { 13cd139dc7SShuo Chen printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); 14cd139dc7SShuo Chen } 15cd139dc7SShuo Chen 16cd139dc7SShuo Chen ~Test() 17cd139dc7SShuo Chen { 18cd139dc7SShuo Chen printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); 19cd139dc7SShuo Chen } 20cd139dc7SShuo Chen 21cd139dc7SShuo Chen const std::string& name() const { return name_; } 22cd139dc7SShuo Chen void setName(const std::string& n) { name_ = n; } 23cd139dc7SShuo Chen 24cd139dc7SShuo Chen private: 25cd139dc7SShuo Chen std::string name_; 26cd139dc7SShuo Chen}; 27cd139dc7SShuo Chen 28cd139dc7SShuo Chenvoid threadFunc(const char* changeTo) 29cd139dc7SShuo Chen{ 30cd139dc7SShuo Chen printf("tid=%d, %p name=%s\n", 31cd139dc7SShuo Chen muduo::CurrentThread::tid(), 32cd139dc7SShuo Chen &muduo::ThreadLocalSingleton<Test>::instance(), 33cd139dc7SShuo Chen muduo::ThreadLocalSingleton<Test>::instance().name().c_str()); 34cd139dc7SShuo Chen muduo::ThreadLocalSingleton<Test>::instance().setName(changeTo); 35cd139dc7SShuo Chen printf("tid=%d, %p name=%s\n", 36cd139dc7SShuo Chen muduo::CurrentThread::tid(), 37cd139dc7SShuo Chen &muduo::ThreadLocalSingleton<Test>::instance(), 38cd139dc7SShuo Chen muduo::ThreadLocalSingleton<Test>::instance().name().c_str()); 39cd139dc7SShuo Chen 40cd139dc7SShuo Chen // manually delete it 41cd139dc7SShuo Chen muduo::ThreadLocalSingleton<Test>::destroy(); 42cd139dc7SShuo Chen} 43cd139dc7SShuo Chen 44cd139dc7SShuo Chenint main() 45cd139dc7SShuo Chen{ 46cd139dc7SShuo Chen muduo::ThreadLocalSingleton<Test>::instance().setName("main one"); 47cd139dc7SShuo Chen muduo::Thread t1(boost::bind(threadFunc, "thread1")); 48cd139dc7SShuo Chen muduo::Thread t2(boost::bind(threadFunc, "thread2")); 49cd139dc7SShuo Chen t1.start(); 50cd139dc7SShuo Chen t2.start(); 51cd139dc7SShuo Chen t1.join(); 52cd139dc7SShuo Chen printf("tid=%d, %p name=%s\n", 53cd139dc7SShuo Chen muduo::CurrentThread::tid(), 54cd139dc7SShuo Chen &muduo::ThreadLocalSingleton<Test>::instance(), 55cd139dc7SShuo Chen muduo::ThreadLocalSingleton<Test>::instance().name().c_str()); 56cd139dc7SShuo Chen t2.join(); 57cd139dc7SShuo Chen} 58