levy5307 / blog

https://levy5307.github.io/blog/
MIT License
0 stars 0 forks source link

Singleton Thread Safe #4

Open levy5307 opened 4 years ago

levy5307 commented 4 years ago

https://levy5307.github.io/blog/singleton-thread-safe/

最近重构rdsn代码,创建了一个logger_proxy类,发现一些单例的线程安全问题,记录如下。

一、懒汉式

最初通过继承singleton的方式来实现的单例,如下: class logger_proxy : public singleton { }

而singleton使用的是静态变量来实现的懒汉式单例: template class singleton { public: singleton() = default;

// disallow copy and assign
singleton(const singleton &) = delete;
singleton &operator=(const singleton &) = delete;

static T &instance()
{
    static T _instance;
    return _instance;
}

};

在运行dsn_nfs_test的时候,当主线程退出时,会子线程会接收到SIGSEGV(signal id = 11),所以子线程会执行第26行的代码,打印该warn日志。 void native_linux_aio_provider::get_event() { struct io_event events[1]; int ret;

task::set_tls_dsn_context(node(), nullptr);

const char *name = ::dsn::tools::get_service_node_name(node());
char buffer[128];
sprintf(buffer, 
yspyhp commented 4 years ago

线程安全是一个大课题