ThreadLocal_test.cc revision cd139dc7
1cd139dc7SShuo Chen#include "../ThreadLocal.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 Chenmuduo::ThreadLocal<Test> testObj1; 28cd139dc7SShuo Chenmuduo::ThreadLocal<Test> testObj2; 29cd139dc7SShuo Chen 30cd139dc7SShuo Chenvoid print() 31cd139dc7SShuo Chen{ 32cd139dc7SShuo Chen printf("tid=%d, obj1 %p name=%s\n", 33cd139dc7SShuo Chen muduo::CurrentThread::tid(), 34cd139dc7SShuo Chen &testObj1.value(), 35cd139dc7SShuo Chen testObj1.value().name().c_str()); 36cd139dc7SShuo Chen printf("tid=%d, obj2 %p name=%s\n", 37cd139dc7SShuo Chen muduo::CurrentThread::tid(), 38cd139dc7SShuo Chen &testObj2.value(), 39cd139dc7SShuo Chen testObj2.value().name().c_str()); 40cd139dc7SShuo Chen} 41cd139dc7SShuo Chen 42cd139dc7SShuo Chenvoid threadFunc() 43cd139dc7SShuo Chen{ 44cd139dc7SShuo Chen print(); 45cd139dc7SShuo Chen testObj1.value().setName("changed 1"); 46cd139dc7SShuo Chen testObj2.value().setName("changed 42"); 47cd139dc7SShuo Chen print(); 48cd139dc7SShuo Chen} 49cd139dc7SShuo Chen 50cd139dc7SShuo Chenint main() 51cd139dc7SShuo Chen{ 52cd139dc7SShuo Chen testObj1.value().setName("main one"); 53cd139dc7SShuo Chen print(); 54cd139dc7SShuo Chen muduo::Thread t1(threadFunc); 55cd139dc7SShuo Chen t1.start(); 56cd139dc7SShuo Chen t1.join(); 57cd139dc7SShuo Chen testObj2.value().setName("main two"); 58cd139dc7SShuo Chen print(); 59cd139dc7SShuo Chen 60cd139dc7SShuo Chen pthread_exit(0); 61cd139dc7SShuo Chen} 62