更新时间:2023-12-08 来源:黑马程序员 浏览量:
当涉及到线程安全的单例模式时,可以使用Python中的线程锁(threading.Lock())来确保只有一个线程能够实例化该类。以下是一个示例:
import threading
class Singleton:
_instance = None
_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
# 示例用法
def create_singleton_instance():
singleton_instance = Singleton()
print(f"Singleton instance ID: {id(singleton_instance)}")
# 创建多个线程来尝试获取单例实例
threads = []
for _ in range(5):
thread = threading.Thread(target=create_singleton_instance)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
这个示例中,Singleton类使用__new__方法来控制实例的创建,确保只有一个实例被创建。_lock是一个 threading.Lock()对象,用于在多线程环境下保护对_instance的访问,防止多个线程同时创建实例。