Use locking when creating singleton
This commit is contained in:
parent
d3a709642b
commit
4927f237ab
@ -1,9 +1,10 @@
|
|||||||
# Standard library imports
|
# Standard library imports
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass
|
||||||
from enum import auto, Enum
|
from enum import auto, Enum
|
||||||
import functools
|
import functools
|
||||||
|
import threading
|
||||||
from typing import NamedTuple
|
from typing import NamedTuple
|
||||||
|
|
||||||
# Third party imports
|
# Third party imports
|
||||||
@ -34,12 +35,18 @@ def singleton(cls):
|
|||||||
"""
|
"""
|
||||||
Make a class a Singleton class (see
|
Make a class a Singleton class (see
|
||||||
https://realpython.com/primer-on-python-decorators/#creating-singletons)
|
https://realpython.com/primer-on-python-decorators/#creating-singletons)
|
||||||
|
|
||||||
|
Added locking.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
lock = threading.Lock()
|
||||||
|
|
||||||
@functools.wraps(cls)
|
@functools.wraps(cls)
|
||||||
def wrapper_singleton(*args, **kwargs):
|
def wrapper_singleton(*args, **kwargs):
|
||||||
if not wrapper_singleton.instance:
|
if wrapper_singleton.instance is None:
|
||||||
wrapper_singleton.instance = cls(*args, **kwargs)
|
with lock:
|
||||||
|
if wrapper_singleton.instance is None: # Check still None
|
||||||
|
wrapper_singleton.instance = cls(*args, **kwargs)
|
||||||
return wrapper_singleton.instance
|
return wrapper_singleton.instance
|
||||||
|
|
||||||
wrapper_singleton.instance = None
|
wrapper_singleton.instance = None
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user