muduo_base程式碼剖析之執行緒本地單例物件ThreadLocalSingleton
阿新 • • 發佈:2018-11-26
執行緒本地單例物件的封裝ThreadLocalSingleton<T>,也就是說,每一個執行緒都有一個T型別的單例物件
直接看測試程式碼
#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()單例物件是每個執行緒都有一份,即每個執行緒都有一個Test物件
//與上一章節看到的完全不一樣
//主執行緒中,叫main one
muduo::ThreadLocalSingleton<Test>::instance().setName("main one");
//執行緒1中,叫thread1
muduo::Thread t1(std::bind(threadFunc, "thread1"));
//執行緒2中,叫thread2
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);
}