import timeimport threadingtry: # 线程和协程都可处理 import greenlet get_ident = greenlet.getcurrentexcept Exception as e: get_ident = threading.get_identclass Local(object): """ 通过进程号/协程号的唯一标识,给每一个进程/协程开辟自己个空间,实现数据隔离 """ DIC = {} def __getattr__(self, item): ident = get_ident() if ident in self.DIC: return self.DIC[ident].get(item) return None def __setattr__(self, key, value): ident = get_ident() if ident in self.DIC: self.DIC[ident][key] = value else: self.DIC[ident] = {key: value}obj = Local()def fn(i): obj.x1 = i time.sleep(2) print(obj.x1,i)for i in range(10): t = threading.Thread(target=fn,args=(i,)) t.start()