Skip to content
Ayotl

← All challenges

Interview challenge · medium · design-pattern, concurrency, oop

Thread-Safe Singleton

The challenge

A singleton is a class that has exactly one instance, with a single global access point, get(). Make it thread-safe: when several threads call get() at the same time, the object must still be built only once, and every thread must receive that same object.

Example

8 threads call get() at the same time
threads 8
built 1       (the constructor ran only once)
same true     (all 8 threads got the same object)

Idea: double-checked locking. The first check, without the lock, is the fast path: once the object exists, get() just returns it. If it does not exist yet, take the lock and check again, because another thread may have built it while this one was waiting; only then build it. The constructor sleeps 10 ms on purpose: without the lock, several threads would get past the check and build their own copy. In C the shared pointer is _Atomic, so reading it outside the lock is safe (Java declares it volatile for the same reason); pthread_once is the other classic way to do it in C. In Python, a module is already a singleton: importing it twice gives back the same object.

The solution

# Thread-Safe Singleton - ayotl.dev
import threading
import time

N = 8  # threads


class Config:
    _inst = None
    _lock = threading.Lock()
    built = 0  # how many were made

    def __init__(self):
        time.sleep(0.01)  # slow build
        Config.built += 1

    @classmethod
    def get(cls):
        # 1st check, no lock: the fast path
        if cls._inst is None:
            with cls._lock:
                # 2nd check: another thread
                # may have built it by now
                if cls._inst is None:
                    cls._inst = cls()
        return cls._inst


got = []


def worker():
    got.append(Config.get())


ts = [threading.Thread(target=worker)
      for _ in range(N)]
for t in ts:
    t.start()
for t in ts:
    t.join()
same = all(c is got[0] for c in got)
print("threads", len(got))
print("built", Config.built)
print("same", "true" if same else "false")

$ python3 thread_safe_singleton.py

threads 8

built 1

same true

The video

Watch on YouTube →