更新時間:2023-12-08 來源:黑馬程序員 瀏覽量:
當涉及到線程安全的單例模式時,可以使用Python中的線程鎖(threading.Lock())來確保只有一個線程能夠?qū)嵗擃悺R韵率且粋€示例:
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)}") # 創(chuàng)建多個線程來嘗試獲取單例實例 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__方法來控制實例的創(chuàng)建,確保只有一個實例被創(chuàng)建。_lock是一個 threading.Lock()對象,用于在多線程環(huán)境下保護對_instance的訪問,防止多個線程同時創(chuàng)建實例。