Upload New File

parent 349c3bbc
import threading
import time
class SafeSingleton:
_instance = None
_lock = threading.Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
time.sleep(0.01)
cls._instance = super(SafeSingleton, cls).__new__(cls)
return cls._instance
instances = []
def create_instance():
instance = SafeSingleton()
instances.append(instance)
if __name__ == "__main__":
threads = [threading.Thread(target=create_instance) for _ in range(10)]
for t in threads:
t.start()
# time.sleep(0.01)
for t in threads:
t.join()
unique_instances = set(instances)
print(f"Создано {len(unique_instances)} уникальных экземпляров Singleton.")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment