草庐IT

c++ - 这个针对 MSVC 双重检查锁定错误和函数静态的解决方案有什么问题?

coder 2024-02-24 原文

尚不完全清楚为什么这不起作用。托管对象仍然被构造两次:

/** Returns an object with static storage duration.
    This is a workaround for Visual Studio 2013 and earlier non-thread
    safe initialization of function local objects with static storage duration.

    Usage:
    @code
    my_class& foo()
    {
        static static_initializer <my_class> instance;
        return *instance;
    }
    @endcode
*/
template <
    class T,
    class Tag = void
>
class static_initializer
{
private:
    T* instance_;

public:
    template <class... Args>
    explicit static_initializer (Args&&... args);

    T&
    get() noexcept
    {
        return *instance_;
    }

    T&
    operator*() noexcept
    {
        return get();
    }

    T*
    operator->() noexcept
    {
        return &get();
    }
};

template <class T, class Tag>
template <class... Args>
static_initializer <T, Tag>::static_initializer (Args&&... args)
{
#ifdef _MSC_VER
    static std::aligned_storage <sizeof(T),
        std::alignment_of <T>::value>::type storage;
    instance_ = reinterpret_cast<T*>(&storage);

    // Double checked lock:
    //  0 = unconstructed
    //  1 = constructing
    //  2 = constructed
    //
    static long volatile state; // zero-initialized
    if (state != 2)
    {
        struct destroyer
        {
            T* t_;
            destroyer (T* t) : t_(t) { }
            ~destroyer() { t_->~T(); }
        };

        for(;;)
        {
            long prev;
            prev = InterlockedCompareExchange(&state, 1, 0);
            if (prev == 0)
            {
                try
                {
                    ::new(instance_) T(std::forward<Args>(args)...);                   
                    static destroyer on_exit (instance_);
                    InterlockedIncrement(&state);
                }
                catch(...)
                {
                    InterlockedDecrement(&state);
                    throw;
                }
            }
            else if (prev == 1)
            {
                std::this_thread::sleep_for (std::chrono::milliseconds(10));
            }
            else
            {
                assert(prev == 2);
                break;
            }
        }
    }

#else
    static T object(std::forward<Args>(args)...);
    instance_ = &object;

#endif
}

最佳答案

我相信下面的代码是正确的。它通过了单元测试。原始代码的问题在于 Visual Studio 2013 及更早版本使用简单的 bool 保护函数局部对象的构造函数。在调用构造函数之前,bool 被设置为 true。因此,其他线程可以将对象视为已完全构建,但实际上并未构建。问题中发布的实现是不正确的,因为 get() 函数可以在完全构造之前访问托管对象。

这个新实现通过旋转来保护 get() 直到对象被完全构建。其余大部分更改围绕使状态数据可供其他成员函数使用。

任何使用支持 C++11 且 2013 或更早版本的 Visual Studio 遇到函数局部静态不是线程安全问题的人都可以替换:

void example()
{
    static MyObject foo;
    foo.bar();
}

void example()
{
    beast::static_initializer <MyObject> foo;
    foo->bar();
}

并修复并发访问具有静态存储持续时间的函数局部对象的问题。代码:

#ifndef BEAST_UTILITY_STATIC_INITIALIZER_H_INCLUDED
#define BEAST_UTILITY_STATIC_INITIALIZER_H_INCLUDED

#include <beast/utility/noexcept.h>
#include <utility>

#ifdef _MSC_VER
#include <cassert>
#include <chrono>
#include <new>
#include <type_traits>
#include <intrin.h>
#endif

namespace beast {

/** Returns an object with static storage duration.
    This is a workaround for Visual Studio 2013 and earlier non-thread
    safe initialization of function local objects with static storage duration.

    Usage:
    @code
    my_class& foo()
    {
        static static_initializer <my_class> instance;
        return *instance;
    }
    @endcode
*/
#ifdef _MSC_VER
template <
    class T,
    class Tag = void
>
class static_initializer
{
private:
    struct data_t
    {
        //  0 = unconstructed
        //  1 = constructing
        //  2 = constructed
        long volatile state;

        typename std::aligned_storage <sizeof(T),
            std::alignment_of <T>::value>::type storage;
    };

    struct destroyer
    {
        T* t_;
        explicit destroyer (T* t) : t_(t) { }
        ~destroyer() { t_->~T(); }
    };

    static
    data_t&
    data() noexcept;

public:
    template <class... Args>
    explicit static_initializer (Args&&... args);

    T&
    get() noexcept;

    T&
    operator*() noexcept
    {
        return get();
    }

    T*
    operator->() noexcept
    {
        return &get();
    }
};

//------------------------------------------------------------------------------

template <class T, class Tag>
auto
static_initializer <T, Tag>::data() noexcept ->
    data_t&
{
    static data_t _; // zero-initialized
    return _;
}

template <class T, class Tag>
template <class... Args>
static_initializer <T, Tag>::static_initializer (Args&&... args)
{
    data_t& _(data());

    // Double Checked Locking Pattern

    if (_.state != 2)
    {
        T* const t (reinterpret_cast<T*>(&_.storage));

        for(;;)
        {
            long prev;
            prev = InterlockedCompareExchange(&_.state, 1, 0);
            if (prev == 0)
            {
                try
                {
                    ::new(t) T (std::forward<Args>(args)...);                   
                    static destroyer on_exit (t);
                    InterlockedIncrement(&_.state);
                }
                catch(...)
                {
                    // Constructors that throw exceptions are unsupported
                    std::terminate();
                }
            }
            else if (prev == 1)
            {
                std::this_thread::yield();
            }
            else
            {
                assert(prev == 2);
                break;
            }
        }
    }
}

template <class T, class Tag>
T&
static_initializer <T, Tag>::get() noexcept
{
    data_t& _(data());
    for(;;)
    {
        if (_.state == 2)
            break;
        std::this_thread::yield();
    }
    return *reinterpret_cast<T*>(&_.storage);
}

#else
template <
    class T,
    class Tag = void
>
class static_initializer
{
private:
    T* instance_;

public:
    template <class... Args>
    explicit
    static_initializer (Args&&... args);

    T&
    get() noexcept
    {
        return *instance_;
    }

    T&
    operator*() noexcept
    {
        return get();
    }

    T*
    operator->() noexcept
    {
        return &get();
    }
};

template <class T, class Tag>
template <class... Args>
static_initializer <T, Tag>::static_initializer (Args&&... args)
{
    static T t (std::forward<Args>(args)...);
    instance_ = &t;
}

#endif

}

#endif

//------------------------------------------------------------------------------

#include <beast/utility/static_initializer.h>
#include <beast/unit_test/suite.h>
#include <atomic>
#include <condition_variable>
#include <sstream>
#include <thread>
#include <utility>

namespace beast {

static_assert(__alignof(long) >= 4, "");

class static_initializer_test : public unit_test::suite
{
public:
    // Used to create separate instances for each test
    struct cxx11_tag { };
    struct beast_tag { };
    template <std::size_t N, class Tag>
    struct Case
    {
        enum { count = N };
        typedef Tag type;
    };

    struct Counts
    {
        Counts()
            : calls (0)
            , constructed (0)
            , access (0)
        {
        }

        // number of calls to the constructor
        std::atomic <long> calls;

        // incremented after construction completes
        std::atomic <long> constructed;

        // increment when class is accessed before construction
        std::atomic <long> access;
    };

    /*  This testing singleton detects two conditions:
        1. Being accessed before getting fully constructed
        2. Getting constructed twice
    */
    template <class Tag>
    class Test;

    template <class Function>
    static
    void
    run_many (std::size_t n, Function f);

    template <class Tag>
    void
    test (cxx11_tag);

    template <class Tag>
    void
    test (beast_tag);

    template <class Tag>
    void
    test();

    void
    run ();
};

//------------------------------------------------------------------------------

template <class Tag>
class static_initializer_test::Test
{
public:
    explicit
    Test (Counts& counts);

    void
    operator() (Counts& counts);
};

template <class Tag>
static_initializer_test::Test<Tag>::Test (Counts& counts)
{
    ++counts.calls;
    std::this_thread::sleep_for (std::chrono::milliseconds (10));
    ++counts.constructed;
}

template <class Tag>
void
static_initializer_test::Test<Tag>::operator() (Counts& counts)
{
    if (! counts.constructed)
        ++counts.access;
}

//------------------------------------------------------------------------------

template <class Function>
void
static_initializer_test::run_many (std::size_t n, Function f)
{
    std::mutex mutex;
    std::condition_variable cond;
    std::atomic <bool> start (false);
    std::vector <std::thread> threads;

    threads.reserve (n);

    {
        std::unique_lock <std::mutex> lock (mutex);
        for (auto i (n); i-- ;)
        {
            threads.emplace_back([&]()
            {
                {
                    std::unique_lock <std::mutex> lock (mutex);
                    while (! start.load())
                        cond.wait(lock);
                }

                f();
            });
        }
        start.store (true);
    }
    cond.notify_all();
    for (auto& thread : threads)
        thread.join();
}

template <class Tag>
void
static_initializer_test::test (cxx11_tag)
{
    testcase << "cxx11 " << Tag::count << " threads";

    Counts counts;

    run_many (Tag::count, [&]()
    {
        static Test <Tag> t (counts);
        t(counts);
    });

#ifdef _MSC_VER
    // Visual Studio 2013 and earlier can exhibit both double
    // construction, and access before construction when function
    // local statics are initialized concurrently.
    //
    expect (counts.constructed > 1 || counts.access > 0);

#else
    expect (counts.constructed == 1 && counts.access == 0);

#endif
}

template <class Tag>
void
static_initializer_test::test (beast_tag)
{
    testcase << "beast " << Tag::count << " threads";

    Counts counts;

    run_many (Tag::count, [&counts]()
    {
        static static_initializer <Test <Tag>> t (counts);
        (*t)(counts);
    });

    expect (counts.constructed == 1 && counts.access == 0);
}

template <class Tag>
void
static_initializer_test::test()
{
    test <Tag> (typename Tag::type {});
}

void
static_initializer_test::run ()
{
    test <Case<  4, cxx11_tag>> ();
    test <Case< 16, cxx11_tag>> ();
    test <Case< 64, cxx11_tag>> ();
    test <Case<256, cxx11_tag>> ();

    test <Case<  4, beast_tag>> ();
    test <Case< 16, beast_tag>> ();
    test <Case< 64, beast_tag>> ();
    test <Case<256, beast_tag>> ();
}

//------------------------------------------------------------------------------

BEAST_DEFINE_TESTSUITE(static_initializer,utility,beast);

}

关于c++ - 这个针对 MSVC 双重检查锁定错误和函数静态的解决方案有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24787259/

有关c++ - 这个针对 MSVC 双重检查锁定错误和函数静态的解决方案有什么问题?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  6. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  7. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  8. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  9. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  10. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

随机推荐