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