flask多线程多协程操作
Posted wanghuaqiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask多线程多协程操作相关的知识,希望对你有一定的参考价值。
local的作用:各个线程各开辟一块空间互不影响
基于local
""" import threading from threading import local import time obj = local() def task(i): obj.xxxxx = i time.sleep(2) print(obj.xxxxx,i) for i in range(10): t = threading.Thread(target=task,args=(i,)) t.start() """ """
基于线程
import threading from threading import local def task(i): print(threading.get_ident(),i) for i in range(10): t = threading.Thread(target=task,args=(i,)) t.start() """ """ import time import threading import greenlet DIC = {} def task(i): # ident = threading.get_ident() ident = greenlet.getcurrent() if ident in DIC: DIC[ident][‘xxxxx‘] = i else: DIC[ident] = {‘xxxxx‘:i } time.sleep(2) print(DIC[ident][‘xxxxx‘],i) for i in range(10): t = threading.Thread(target=task,args=(i,)) t.start() """
基于协程
import time import threading try: import greenlet get_ident = greenlet.getcurrent except Exception as e: get_ident = threading.get_ident class 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 task(i): obj.xxxxx = i time.sleep(2) print(obj.xxxxx,i) for i in range(10): t = threading.Thread(target=task,args=(i,)) t.start()
以上是关于flask多线程多协程操作的主要内容,如果未能解决你的问题,请参考以下文章