我正在学习如何实现线程安全的单例模式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
标记并尝试使用系统上本机线程库中的实用程序。
作为替代方案,请查看示例中对单例模式定义的以下更改(称为“Meyers Singleton”)
Singleton& Singleton::get_instance(){
static Singleton instance;
return instance;
}
这是线程安全的,并且会导致instance
变量只能初始化一次。这篇维基百科文章很好地解释了它的幕后工作原理https://en.wikipedia.org/wiki/Double-checked_locking https://en.wikipedia.org/wiki/Double-checked_locking。尽可能让编译器为您安排代码是件好事。也如评论中所述 https://stackoverflow.com/questions/44653808/stdsystem-exception-when-instantiating-a-singleton-object/44654004#comment76292952_44653808这个问题也有关于上述内容的有用信息Meyers 的单例模式实现线程安全吗? https://stackoverflow.com/questions/1661529/is-meyers-implementation-of-the-singleton-pattern-thread-safe
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)