我正在学习如何在以后实现线程安全的单例模式c++11
。
#include <iostream>
#include <memory>
#include <mutex>
class Singleton
{
public:
static Singleton& get_instance();
void print();
private:
static std::unique_ptr<Singleton> m_instance;
static std::once_flag m_onceFlag;
Singleton(){};
Singleton(const Singleton& src);
Singleton& operator=(const Singleton& rhs);
};
std::unique_ptr<Singleton> Singleton::m_instance = nullptr;
std::once_flag Singleton::m_onceFlag;
Singleton& Singleton::get_instance(){
std::call_once(m_onceFlag, [](){m_instance.reset(new Singleton());});
return *m_instance.get();
};
void Singleton::print(){
std::cout << "Something" << std::endl;
}
int main(int argc, char const *argv[])
{
Singleton::get_instance().print();
return 0;
}
代码编译得很好,但在执行时我收到以下异常。
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted
我试图用gdb
. 好像是调用的时候抛出了异常std::call_once
。我不确定发生了什么,但我认为 lambda 表达式未能创建对象。
第二个问题。有没有办法知道未知错误代码的实际含义?我认为-1
在尝试确定问题时不会有太大帮助。
谢谢你的帮助。
发生这种情况是因为您没有使用该-pthread
标志进行编译,而是尝试使用系统上本机线程库中的实用程序。
作为另一种方式查看您的示例中的单例模式定义的以下更改,称为“迈耶斯单例”
Singleton& Singleton::get_instance(){
static Singleton instance;
return instance;
}
这是线程安全的,并且会导致instance
变量只被初始化一次。这篇维基百科文章很好地解释了它如何在幕后工作https://en.wikipedia.org/wiki/Double-checked_locking。最好让编译器尽可能为您安排代码。同样如评论中所述,这个问题也有关于上述的有用信息Meyers 对单例模式线程的实现是否安全?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句