1、先来看一段多线程代码:
std::shared_ptr<some_resource> resource_prtr;
std::mutex resource_mutex;
void foo()
{
std::unique_lock<std::mutex> lk(resource_mutex);
//此处所有线程序列化
if(!resource_ptr)
{
resource_ptr.reset(new some_resource);//1,只有初始化过程需要保护
}
lk.unlock();
resource_ptr->so_something();
}
由上一段代码可知,为了确定数据源已经初始化,每个线程都必须等待互斥量,可见没必要。
2、有人改进的双重检测锁模式:
void undefined_behaviour_with_double_checked_locing()
{
if(!resource_ptr) //1
{
std::lock_guard<std::mutex> lk(resource_mutex);
if(!!resource_ptr) //2