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