码迷,mamicode.com
首页 > 编程语言 > 详细

shared_ptr 线程安全

时间:2016-11-08 19:36:58      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:actual   atom   cti   proc   lis   final   certainly   eth   live   

Then what‘s really happening is TWO different sections of memory are being allocated. It‘s done at one time,
 but it‘s two "logical" blocks. One is the int which stores the actual value, and the other is the control block,
 which stores all the shared_ptr "magic" that makes it work.
It is only the control block itself which is thread-safe.
shared_ptr<int> global_ptr = make_shared<int>(0);
void thread_fcn();
int main(int argc, char** argv)
{
    thread thread1(thread_fcn);
    thread thread2(thread_fcn);
    ...
    thread thread10(thread_fcn);
    chrono::milliseconds duration(10000);
    this_thread::sleep_for(duration);
    return;
}
void thread_fcn()
{
    // This is thread-safe and will work fine, though it‘s useless.  Many
    // short-lived pointers will be created and destroyed.
    for(int i = 0; i < 10000; i++)
    {
        shared_ptr<int> temp = global_ptr;
    }
    // This is not thread-safe.  While all the threads are the same, the
    // "final" value of this is almost certainly NOT going to be
    // number_of_threads*10000 = 100,000.  It‘ll be something else.
    for(int i = 0; i < 10000; i++)
    {
        *global = *global + 1;
    }
}
C++标准库为std::shared_ptr提供了一些重要的辅助函数,让这些智能指针可以以“原子操作”的方式获取值,设置值.
std::shared_ptr<my_data> p;
void process_global_data()
{
    std::shared_ptr<my_data> local=std::atomic_load(&p);
    process_data(local);
}
void update_global_data()
{
    std::shared_ptr<my_data> local(new my_data);
    std::atomic_store(&p,local);
}
So if you do: it will be thread safe.
//In thread 1
shared_ptr<myClass> private = atomic_load(&global);
...
//In thread 2
atomic_store(&global, make_shared<myClass>());...

shared_ptr 线程安全

标签:actual   atom   cti   proc   lis   final   certainly   eth   live   

原文地址:http://www.cnblogs.com/abelian/p/6043999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!