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