【发布时间】:2011-09-30 06:36:22
【问题描述】:
考虑以下 C++ 单例实现,将 pthread_once 用于 线程安全初始化:
class MySingleton
{
public:
static MySingleton* Instance();
protected:
MySingleton() {};
static void InitOnce();
private:
static MySingleton* instance;
};
MySingleton* MySingleton::instance = NULL;
pthread_once_t singleton_once_control = PTHREAD_ONCE_INIT;
MySingleton* MySingleton::Instance()
{
pthread_once(&singleton_once_control, &InitOnce);
return instance;
}
void MySingleton::InitOnce()
{
instance = new MySingleton;
}
问题是 pthread_once 需要回调函数具有 C 链接。 (好的,这只是一个编译器警告,在我正在测试的环境中 该代码有效,因为 C 和 C++ 函数调用约定是二进制兼容的)
但是对于真正的跨平台解决方案有什么好的模式吗?您可以创建一个 C 链接包装函数,但它不能是类的一部分,因此调用私有 init 函数 InitOnce。
任何避免公开 InitOnce 的解决方案?
附:是的,单身人士很糟糕。让我们不要这样说......
【问题讨论】:
标签: c++ c thread-safety singleton pthreads