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多线程多协程操作的主要内容,如果未能解决你的问题,请参考以下文章

玩转pythonpython多协程,多线程的比较

分布式计算--(分布式+多进程+多线程+多协程)

python 复习—并发编程实战——线程多进程多协程加速程序运行实例(多线程和多进程的对比)

think-swoole当中多协程进行访问

golang 单协程和多协程的性能测试

怎样部署Flask服务?使用Gevent快速改造成高性能服务器