多线程和模板化单例竞争条件

Multi Threaded and templated singleton race condition

作为我高级 C++ 学习的一部分,我正在尝试创建一个多线程和模板化单例。有人告诉我我的代码中存在竞争条件,经过数小时的尝试后我找不到它。

我不会写完整的 class(虽然它很简单)但是我一直关注的确切位置:

template <class T>
void Singleton<T>::onceFunction()
{
    static T instanceObject; 
    Singleton<T>::instance = &instanceObject;
}

template <class T>
T& Singleton<T>::getInstance()
{
    while (0 == Singleton::instance)
    {
        static pthread_once_t  once_control = PTHREAD_ONCE_INIT;
        pthread_once(&once_control, Singleton<T>::onceFunction);  
    }
    return *Singleton::instance;
}

我正在使用 pthread_once() 因为我没有使用 c++11 进行编译。

您显示的代码旨在protect/serialize

的初始化
static T instanceObject;

Singleton<T>::onceFunction() 中所定义。为了实现这一点,您使用 pthread_once。但是,您已在具有静态存储的 function/block 范围内声明了 pthread_once_t 标志 once_control...

static pthread_once_t  once_control = PTHREAD_ONCE_INIT;

因此,我认为 once_control 的初始化遇到与您的代码旨在解决 instanceObject.

相同的竞争条件

使 once_control 成为 Singleton<T> 的静态成员。

注意:您的代码还承担了赋值...

Singleton<T>::instance = &instanceObject;

是原子的。