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