在Python中实现线程安全的单例模式,我们需要确保即使在多线程环境中,单例类也只会被实例化一次。下面是一个使用 `__new__` 方法实现线程安全的单例模式的例子:
```python
import threading
class Singleton:
# 创建一个类级别的锁
_lock = threading.Lock()
_instance = None
def __new__(cls, *args, **kwargs):
# 在创建新实例之前获取锁
with cls._lock:
if not cls._instance:
# 如果实例不存在,则创建一个实例
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
# 初始化实例的属性
self.data = "This is a singleton instance"
# 使用Singleton类
if __name__ == "__main__":
# 创建线程
def run_singleton():
instance = Singleton