多线程执行单例模式,有BUG
import threading import time class Singleton: instance = None def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): if cls.instance: return cls.instance time.sleep(0.1) cls.instance = object.__new__(cls) return cls.instance def task(): obj = Singleton(\'x\') print(obj) for i in range(10): t = threading.Thread(target=task) t.start()
加锁解决BUG
import threading import time class Singleton: instance = None lock = threading.RLock() def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): with cls.lock: if cls.instance: return cls.instance time.sleep(0.1) cls.instance = object.__new__(cls) return cls.instance def task(): obj = Singleton(\'x\') print(obj) for i in range(10): t = threading.Thread(target=task) t.start()
加判断,提升性能
import threading import time class Singleton: instance = None lock = threading.RLock() def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): if cls.instance: return cls.instance with cls.lock: if cls.instance: return cls.instance time.sleep(0.1) cls.instance = object.__new__(cls) return cls.instance def task(): obj = Singleton(\'x\') print(obj) for i in range(10): t = threading.Thread(target=task) t.start() # 执行1000行代码 data = Singleton(\'asdfasdf\') print(data) 本篇总结进程和线程的区别
什么是GIL锁
多线程和线程池的使用。
线程安全 & 线程锁 & 死锁