1.Java类型
1.1 双重检查锁定(Double-Checked Locking)
public class Singleton {
// 使用volatile关键字可以确保在多线程环境下对instance的修改可见性
private static volatile Singleton instance;
private Singleton() {
// 私有构造函数,防止外部实例化
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
1.2 静态内部类
这种方式利用了类加载的特性,只有在第一次调用getInstance时,JVM才会加载SingletonHolder类,从而实例化Singleton对象
public class Singleton {
private Singleton() {
// 私有构造函数,防止外部实例化
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
1.3 枚举实现:
枚举实现是线程安全的,并且防止通过反射和序列化破坏单例。
public enum LazyLoadedSingleton {
INSTANCE;
// 可以添加其他成员变量和方法
}
2.Python类型
# refer: https://www.cnblogs.com/huchong/p/8244279.html
# 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类
# 只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场
import time
import threading
# 基于__new__方法实现(推荐使用,方便)
# 当我们实现单例时,为了保证线程安全需要在内部加入锁
#
# 我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),
# 实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
# see: java double-check locking for singleton mode
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls)
# 每个类实例对象时,都会调用 __new__,__init__方法。
# 而这个单列模式只能在这里创建rlock锁。在__init__方法内创建rlock锁,
# 不是唯一的。不能保证数据安全
Singleton._instance.id = 0
Singleton._instance.lock = threading.RLock()
return Singleton._instance
# 通过使用
# Lock
# 对象可以非常方便地实现线程安全的类,线程安全的类具有如下特征:
# 该类的对象可以被多个线程安全地访问。
# 每个线程在调用该对象的任意方法之后,都将得到正确的结果。
# 每个线程在调用该对象的任意方法之后,该对象都依然保持合理的状态。
def increaseId(self):
self.lock.acquire()
try:
# time.sleep(2)
self.id = self.id + 1
print("self.addr=%d self.id=%d self.id.addr=%d" % (id(self), self.id, id(self.id)))
finally:
self.lock.release()
def task(arg):
print(type(arg), arg)
obj = Singleton()
obj.increaseId()
# print("obj,id(obj.id),id(obj.lock)",obj,id(obj.id),id(obj.lock))
def testSingleton2():
# obj1 = Singleton()
# obj2 = Singleton()
# obj1.increaseId()
# obj2.increaseId()
for i in range(2):
t = threading.Thread(target=task, args=[i, ])
t.start()
if __name__ == '__main__':
# testSingleton1()
testSingleton2()
3.C++类型
3.1 双重检查锁定(Double-Checked Locking):
这里使用了std::mutex来保护对instance的访问,确保在多线程环境中只有一个线程可以创建实例。
#include <iostream>
#include <mutex>
class Singleton {
private:
static Singleton* instance;
static std::mutex mutex;
Singleton() {
// 私有构造函数,防止外部实例化
}
public:
static Singleton* getInstance() {
if (instance == nullptr) {
std::lock_guard<std::mutex> lock(mutex);
if (instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;
3.2 局部静态变量:
C++11引入了线程安全的局部静态变量,它会在第一次调用getInstance时被初始化,且初始化是线程安全的。
#include <iostream>
#include <mutex>
class Singleton {
private:
Singleton() {
// 私有构造函数,防止外部实例化
}
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
3.3 使用std::call_once:
c++11还引入了std::call_once,可以用于保证只有一个线程执行一次代码块
#include <iostream>
#include <mutex>
class Singleton {
private:
Singleton() {
// 私有构造函数,防止外部实例化
}
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
int main() {
Singleton* singleton = Singleton::getInstance();
return 0;
}