pthread_once 确保一个被注册的子函数至多被执行一次:
#include <pthread.h>
#include <cassert>
using namespace std;
class Singleton
{
public:
static
Singleton *instance();
private:
static
Singleton *instance_;
static
pthread_once_t once;
static
void _instance();
Singleton();
};
Singleton::Singleton()
{
};
Singleton *Singleton::instance_ = NULL;
void Singleton::_instance()
{
assert(NULL == instance_);
instance_ = new Singleton();
}
pthread_once_t Singleton::once = PTHREAD_ONCE_INIT;
Singleton *Singleton::instance()
{
pthread_once(&once, Singleton::_instance);
return instance_;
}
下面这段代码,看起来非常和谐的 double-check,what problem?
pthread_mutex_t singleton_mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton *Singleton::instance2()
{
if (NULL == instance_) {
pthread_mutex