采用线程本地存储,我们为每个线程创建一个各自独立的日志对象,并交由一个全局的thread_specific_ptr进行管理,在各个线程中,可以通过这个thread_specific_ptr独立地访问各自线程的日志对象,最后在线程退出的时候,我们再将各个线程的独自记录的日志合并到一起,就成了完整的日志。在这个过程中,各个线程通过thread_sp
boost::thread_specific_ptr<int>ptr;structstcount { stcount(intid) : id(id) { }voidoperator()() {if(ptr.get() ==0) ptr.reset(newint(0));for(inti =0; i <10; ++i) { (*ptr)++; boost::mutex::scoped_locklock(io_mutex); std::cout<< id <<":"<< *ptr <<std::endl; }...
问为什么我们需要boost::thread_specific_ptr?EN传统IT技术团队中通常都有多个独立的组织-开发团队、测试...
也叫线程特有存储:thread specific storage(简称TSS)或线程私有存储:thread private storage。名字太多,...
Boost是由C++标准委员会类库工作组成员发起,致力于为C++开发新的类库的组织。现在它已经有近2000名成员。许多库都可以在Boost源码的发布版本中找到。为了使这些类库是线程安全的(thread-safe),Boost线程库被创建了。 Boost线程库的所有接口设计都是从0开始的,并不是C线程API的简单封装。许多C++特性(比如构造函数和析...
boost::thread thrd(&hello); thrd.join();return0; } 2 互斥体 任何写过多线程程序的人都知道避免不同线程同时访问共享区域的重要性。如果一个线程要改变共享区域中某个数据,而与此同时另一线程正在读这个数据,那么结果将是未定义的。为了避免这种情况的发生就要使用一些特殊的原始类型和操作。其中最基本的就是...
1 class thread_specific_ptr : private boost::noncopyable // Exposition only 2 { 3 public: 4 // construct/copy/destruct 5 thread_specific_ptr(); 6 thread_specific_ptr(void (*cleanup)(void*)); 7 ~thread_specific_ptr(); 8 9 // modifier functions ...
static boost::thread_specific_ptr<int> sp;//该变量是线程独立拥有的 1. if (!sp.get()) 1. { 1. sp.reset(newint(0)); 1. } 1. *sp = n + *sp; 1. return *sp; 1. } 1. 1. voidSum() 1. { 1. cout << Add(5) + Add(10) << endl;//得到的结果20 ...
thread_specific_ptr<MyStruct> ptr; struct MyThread { MyThread(int id) :id(id){} void operator()() { // 如果ptr内部为0则说明没有,我们就初始化为0 if (ptr.get() == 0) ptr.reset(new MyStruct(0,"lyshark")); for (int x = 0; x <10; ++x) { // 往自己的线程上加 (*ptr)...
下面的例子演示怎样将shared_ptr 用于std::vector 中: typedef boost::shared_ptr<CTest> TestPtr; void PT(const TestPtr &t) { std::cout << "id: " << t->GetId() << "/t/t" << "use count: " << t.use_count() << '/n'; ...