shared_ptr 线程安全

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>());...

转载于:https://www.cnblogs.com/abelian/p/6043999.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值