先看下应用:

import threading
from threading import local
import time obj = local() def task(i):
obj.xxxxx = i
time.sleep()
print(obj.xxxxx,i) for i in range():
t = threading.Thread(target=task,args=(i,))
t.start()

上述代码实现了线程间的隔离,为每个线程开辟了独立的空间,这就是threading.local的作用

再看下面代码

import time
import threading DIC = {} def task(i): ident = threading.get_ident()
if ident in DIC:
DIC[ident]['xxxxx'] = i
else:
DIC[ident] = {'xxxxx':i }
time.sleep() print(DIC[ident]['xxxxx'],i) for i in range():
t = threading.Thread(target=task,args=(i,))
t.start()

上述代码使用字典实现了和threading.local一样的功能,其实就是threading.local实现的原理。

再看下面代码:

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() print(DIC[ident]['xxxxx'],i) for i in range():
t = threading.Thread(target=task,args=(i,))
t.start()

上面代码就是threading.local功能的加强版:支持协程!

接着看:

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()
print(obj.xxxxx,i) for i in range():
t = threading.Thread(target=task,args=(i,))
t.start()

上述代码自己实现了threading.local的数据隔离,并支持协程。

threading.local作用及原理的更多相关文章

  1. threading.local()使用与原理剖析

    threading.local()使用与原理剖析 前言 还是第一次摘出某个方法来专门写一篇随笔,哈哈哈. 为什么要写这个方法呢?因为它确实太重要了,包括后期的Flask框架源码中都有它的影子. 那么我 ...

  2. 线程锁、threading.local(flask源码中用的到)、线程池、生产者消费者模型

    一.线程锁 线程安全,多线程操作时,内部会让所有线程排队处理.如:list/dict/Queue 线程不安全 + 人(锁) => 排队处理 1.RLock/Lock:一次放一个 a.创建10个线 ...

  3. 锁,threading local,以及生产者和消费者模型

    1.锁:Lock(一次放行一个) 线程安全,多线程操作时,内部会让所有的线程排队处理. 线程不安全:+人=>排队处理 以后锁代码块 v=[] lock=threading.Lock()#声明锁 ...

  4. 多线程threading.local的作用及原理?

    1.示例代码 import time import threading v = threading.local() def func(arg): # 内部会为当前线程创建一个空间用于存储:phone= ...

  5. threading.local的作用?

    threading.local()这个方法的特点用来保存一个全局变量,但是这个全局变量只有在当前线程才能访问,如果你在开发多线程应用的时候  需要每个线程保存一个单独的数据供当前线程操作,可以考虑使用 ...

  6. flask上下文管理相关 - threading.local 以及原理剖析

    threading.local 面向对象相关: setattr/getattr class Foo(object): pass obj = Foo() obj.x1 = 123 # object.__ ...

  7. 自定义threading.local

    1.threading相关. # Author:Jesi # Time : 2018/12/28 14:21 import threading import time from threading i ...

  8. 锁、threading.local、线程池

    一.锁 Lock(1次放1个) 什么时候用到锁: 线程安全,多线程操作时,内部会让所有线程排队处理.如:list.dict.queue 线程不安全, import threading import t ...

  9. 网络编程 多线程/socketserver模块/ threading.local

    线程:进程中负责程序执行的执行单元. 多线程:在1个进程中存在多个线程. 进程只是用来把资源集中在一起,而线程才是cpu上的执行单位. 每个进程都会默认有一个控制线程也叫作主线程. 进程之间是竞争关系 ...

随机推荐

  1. Http常见的响应头

    Location: http://www.it315.org/index.jsp   -表示重定向的地址,该头和302的状态码一起使用. Server:apache tomcat            ...

  2. 如何解决错误【selenium.common.exceptions.SessionNotCreatedException】

    如何解决错误[selenium.common.exceptions.SessionNotCreatedException]   [问题起因] 2018年12月26日晚,启动我的pycharm准备学习s ...

  3. flask包request获取参数

    原博文:https://www.cnblogs.com/wangjikun/p/6935592.html request.method #获取请求方法request.form #获取post请求所有参 ...

  4. nagios配置邮件告警

    1.编辑配置文件 vim /etc/nagios/objects/contacts.cfg增加如下内容:define contactgroup{ contactgroup_name admins al ...

  5. 47全排列II

    题目:给定一个可包含重复数字的序列,返回所有不重复的全排列. 示例: 输入:[1,1,2]输出:[[1,1,2],[1,2,1],[2,1,1]] 来源:https://leetcode-cn.com ...

  6. fcitx无法切换到中文(manjaro)

    安装fcitx后不能切换到中文输入法,在.bashrc或者.profile中添加以下代码: #fcitx export GTK_IM_MODULE=fcitx  export QT_IM_MODULE ...

  7. java:Oracle(事务,分页,jdbc)Mysql(jdbc)

    1.事务:transaction -- 事务开启的唯一条件就是:对数据库进行增,删,改的时候 -- 换句话说,对数据进行增删改以后,必须要执行提交或者回滚 -- 事务就是把数据库中的数据从一致状态转换 ...

  8. Java重写祖先类方法equals示例

    Java中很重要的一个知识点就是所有类都默认继承Object类,所以创建的每一个类都继承了Object的方法,所有类都可以向上转型为Object类对象,当然可以重写Object里面的常用方法,有时候重 ...

  9. jinja2模板接受

    from flask import Flask,render_template app = Flask(__name__)#template_folder='templates',默认就是templa ...

  10. [Python3] 030 常用模块 os

    目录 os 1. os.getcwd() 2. os.chdir() 3. os.listdir() 4. os.makedir() 5. os.system() 6. os.getenv() 7. ...