shared_ptr线程安全问题

 

shared_ptr 是引用计数型(reference counting)智能指针,几乎所有的实现都采用在堆(heap)上放个计数值(count)的办法。

官方对shared_ptr基本介绍: http://en.cppreference.com/w/cpp/memory/shared_ptr

madn:https://docs.microsoft.com/en-us/cpp/standard-library/shared-ptr-class?view=vs-2019


需要从两个层面进行考虑其线程安全性:

1) shared_ptr本身的线程安全性,例如,引用计数的正确性。
shared_ptr的引用计数是线程安全的,这是由库内部实现的。 如果,让程序员再去维护引用计算的安全性,那这个东西就太不好用了!

另外,多线程下,由于shared_ptr需要维护引用计数的安全,这会造成一定的开销(最新的实现可能已经使用了lock-free的方式了)。 

 

2)shared_ptr所托管的对象的线程安全性。
shared_ptr并不会改变其托管的对象的本身的线程安全性。

 


例1: 多个线程对同一个shared_ptr对象进行改写(改变其指向的资源)操作时,不安全!

https://stackoverflow.com/questions/14482830/stdshared-ptr-thread-safety


// In main()
shared_ptr<myClass> global_instance = make_shared<myClass>();
// (launch all other threads AFTER global_instance is fully constructed)


//In thread 2
global_instance = make_shared<myClass>();

定义一个全局变量global_instance,其可以被所有其他的线程访问。上面线程2胆大包天地改了全局变量的值,从而会影响到其他使用这个全局变量的线程。   -- 不仅仅是shared_ptr,对于其他类型的变量都不能这样子搞~
 

这种情况是安全的: 很多个线程存在,但是仅仅去读global_instance。

 

 

例2: shared_ptr所托管的对象的线程安全性需要coder自己保证:

The thread-safety of the shared_ptr<> instances only applies to managing shared_ptr<> instances which were initialized from each other, not what they're pointing to.

shared_ptr<int> global_instance = 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_instance;
    }

    // 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_instance = *global_instance + 1;
    }
}

 

用std::thread和join体验以下多线程吧:

a) 两个线程交替打印,执行了std::thread的定义之后,线程就开始运行了,并不是等到join函数执行的时候才开始运行哦!join函数的作用仅仅是让主线程等待其他线程的结束。

#include <thread>
#include <mutex>
#include <iostream>

void thread_3()
{
	for (int i = 0; i < 100; i++) {
		std::cout << "Thread 3\n";
	}
}
void thread_4()
{
	for (int i = 0; i < 100; i++) {
		std::cout << "Thread 4\n";
	}
}

int main()
{
	
	//交替打印3 4 
	thread threadG(thread_3);
	thread threadH(thread_4);

	threadG.join();
	threadH.join();
}

 

b)不加锁时,不能得到准确的累加结果。 

启动了 6个线程对一个全局变量进行累加,不加锁的话,不能得到正确的最终结果:10*10000*6.

加锁的话可以用mutex锁,也可以用c++ 的automic原子类型( https://blog.csdn.net/qq_35865125/article/details/105611985 )。


#include <thread>
#include <mutex>
#include <iostream>
void thread_2()
{
	for (int i = 0; i < 10*10000; i++) {
		//std::lock_guard<mutex> lockGuard(g_mutex);//加锁才能保证最后结果的正确
		g_var++;
	}
	std::cout << "Thread 2 finished. \n";
}


int g_var=0;
int main()
{
    std::cout << "Hello World!\n"; 


	thread threadA(thread_2);
	thread threadB(thread_2);
	thread threadC(thread_2);
	thread threadD(thread_2);
	thread threadE(thread_2);
	thread threadF(thread_2);

	threadA.join();
	threadB.join();
	threadC.join();
	threadD.join();
	threadE.join();
	threadF.join();
//将g_var用shared_ptr进行托管,也不能解决问题。需要加锁
	cout << "g_var= " << g_var << endl<<endl; 
	
	
	
}

 

 


May <C++ Concurrency in Action 2nd Edition> will give an ansower!

 


https://www.cnblogs.com/gqtcgq/p/7492772.html 对boost的shared_ptr线程安全的讲解。

该作者的下面这段介绍,非常清晰地总结了shared_ptr的基本原理,向别人讲解时,非常适用!:

shared_ptr 是引用计数型(reference counting)智能指针,几乎所有的实现都采用在堆(heap)上放个计数值(count)的办法(除此之外理论上还有用循环链表的办法,不过没有实例)。

具体来说,shared_ptr<Foo> 包含两个成员,一个是指向 Foo 的指针 ptr,另一个是 ref_count 指针(其类型不一定是原始指针,有可能是 class 类型,但不影响这里的讨论),指向堆上的 ref_count 对象。ref_count 对象有多个成员,具体的数据结构如图 1 所示,其中 deleter 和 allocator 是可选的。

 

 

 


Ref:

https://blog.csdn.net/jiangfuqiang/article/details/8292906

 

 

https://blog.csdn.net/weixin_41966991/article/details/81071507

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值