python - Thread safety issues about singletons
给我你的怀抱
给我你的怀抱 2017-05-18 10:45:22
0
1
545
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?

给我你的怀抱
给我你的怀抱

reply all (1)
刘奇

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.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!