class Singleton(object): __instance = None def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls.__instance if __name__ == '__main__': # 多线程中单例的使用 from threading import Thread def func(): print(id(Singleton())) for index in range(10000): Thread(target=func).start()
The above is a way to implement a singleton in python, but we all know that this implementation is not thread-safe. In the above code, I wrote the test code myself, but found that the id output was the same. This cannot prove that it is not thread-safe? My question is: How to write test code that can prove that this implementation is not thread-safe?
Originally, the singleton mode can only instantiate one object and has nothing to do with threads. Even though it is thread safe, it returns the same id.