线程本地单例对象的封装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);
}