更新時(shí)間:2023-12-08 來源:黑馬程序員 瀏覽量:
當(dāng)涉及到線程安全的單例模式時(shí),可以使用Python中的線程鎖(threading.Lock())來確保只有一個(gè)線程能夠?qū)嵗擃?。以下是一個(gè)示例:
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)建多個(gè)線程來嘗試獲取單例實(shí)例 threads = [] for _ in range(5): thread = threading.Thread(target=create_singleton_instance) threads.append(thread) thread.start() for thread in threads: thread.join()
這個(gè)示例中,Singleton類使用__new__方法來控制實(shí)例的創(chuàng)建,確保只有一個(gè)實(shí)例被創(chuàng)建。_lock是一個(gè) threading.Lock()對象,用于在多線程環(huán)境下保護(hù)對_instance的訪問,防止多個(gè)線程同時(shí)創(chuàng)建實(shí)例。