Home  >  Q&A  >  body text

python - Thread safety issues about singletons


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?

给我你的怀抱给我你的怀抱2711 days ago584

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-18 10:47:22

    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.

    reply
    0
  • Cancelreply