File tree Expand file tree Collapse file tree 1 file changed +13
-3
lines changed Expand file tree Collapse file tree 1 file changed +13
-3
lines changed Original file line number Diff line number Diff line change 5
5
import inspect
6
6
import os
7
7
import random
8
+ import threading
8
9
from abc import ABC , abstractmethod
9
10
from contextlib import contextmanager
10
11
from datetime import datetime
@@ -169,18 +170,27 @@ def __call__(self, batch_count):
169
170
170
171
class SingletonMeta (type ):
171
172
"""
172
- Singleton Meta.
173
+ Thread-safe Singleton Meta with double-checked locking.
174
+ Reference: https://en.wikipedia.org/wiki/Double-checked_locking
173
175
"""
174
176
175
177
_instances = {}
178
+ _lock = threading .Lock ()
176
179
177
180
def __call__ (cls , * args , ** kwargs ):
181
+ # First check (without locking) for performance reasons
178
182
if cls not in cls ._instances :
179
- cls ._instances [cls ] = super ().__call__ (* args , ** kwargs )
183
+ # Acquire a lock before proceeding to the second check
184
+ with cls ._lock :
185
+ # Second check with lock held to ensure thread safety
186
+ if cls not in cls ._instances :
187
+ instance = super ().__call__ (* args , ** kwargs )
188
+ cls ._instances [cls ] = instance
180
189
else :
181
190
assert (
182
191
len (args ) == 0 and len (kwargs ) == 0
183
- ), f"{ cls .__name__ } is a singleton class and a instance has been created."
192
+ ), f"{ cls .__name__ } is a singleton class and an instance has been created."
193
+
184
194
return cls ._instances [cls ]
185
195
186
196
You can’t perform that action at this time.
0 commit comments