pthread_once多线程安全
pthread_once(pthread_once_t *once, void (*init_routine) (void))
在多线程编程环境下,尽管pthread_once()调用会出现在多个线程中,init_routine()函数仅执行一次,究竟在哪个线程中执行是不定的,是由内核调度来决定。
Linux Threads使用互斥锁和条件变量保证由pthread_once()指定的函数执行且仅执行一次,而once_control表示是否执行过。
采用pthread_once实现单例
// singletion.h
#include <pthread.h>
template <typename T>
class Singleton
{
public:
static T* instance()
{
pthread_once(&once, &Singleton::init);
return value;
}
Singleton() = delete;
~Singleton() = delete;
private:
static T* value;
static pthread_once_t once;
static void init()
{
value = new T();
atexit(destory);
}
static void destory()
{
delete value;
}
};
template <typename T> T* Singleton<T>::value = nullptr;
template <typename T> pthread_once_t Singleton<T>::once = PTHREAD_ONCE_INIT;
测试程序
#include "singleton.h"
class Test1
{
public:
Test1()
{
value = "test1";
}
void print()
{
std::cout << value << std::endl;
}
std::string value;
};
class Test2
{
public:
Test2()
{
value = "test2";
}
void print()
{
std::cout << value << std::endl;
}
std::string value;
};
int main()
{
Test1 *p1 = Singleton<Test1>::instance();
Test2 *p2 = Singleton<Test2>::instance();
Test1 *p11 = Singleton<Test1>::instance();
Test2 *p21 = Singleton<Test2>::instance();
p1->print(); // test1
p2->print(); // test2
p11->print(); // test1
p21->print(); // test2
p1->value = "test11";
p2->value = "test21";
p1->print(); // test11
p2->print(); // test21
p11->print(); // test11
p21->print(); // test21
}