Python thread local
class Widgt(object):
pass import threading
def test():
local_data = threading.local()
# local_data = Widgt()
local_data.x = 1 def thread_func():
print('Has x in new thread: %s' % hasattr(local_data, 'x'))
local_data.x = 2 t = threading.Thread(target = thread_func)
t.start()
t.join()
print('x in pre thread is %s' % local_data.x) if __name__ == '__main__':
test()
try:
from thread import _local as local
except ImportError:
from _threading_local import local
class _localbase(object):
__slots__ = '_local__key', '_local__args', '_local__lock' def __new__(cls, *args, **kw):
self = object.__new__(cls)
key = '_local__key', 'thread.local.' + str(id(self)) # 产生一个key,这个key在同一个进程的多个线程中是一样的
object.__setattr__(self, '_local__key', key)
object.__setattr__(self, '_local__args', (args, kw))
object.__setattr__(self, '_local__lock', RLock()) # 可重入的锁 if (args or kw) and (cls.__init__ is object.__init__):
raise TypeError("Initialization arguments are not supported") # We need to create the thread dict in anticipation of
# __init__ being called, to make sure we don't call it
# again ourselves.
dict = object.__getattribute__(self, '__dict__')
current_thread().__dict__[key] = dict # 在current_thread这个线程唯一的对象的—__dict__中加入 key return self def _patch(self):
key = object.__getattribute__(self, '_local__key')
d = current_thread().__dict__.get(key) # 注意 current_thread 在每一个线程是不同的对象
if d is None: # 在新的线程第一次调用时
d = {} # 一个空的dict !!!
current_thread().__dict__[key] = d
object.__setattr__(self, '__dict__', d) # 将实例的__dict__赋值为 线程独立的一个字典 # we have a new instance dict, so call out __init__ if we have
# one
cls = type(self)
if cls.__init__ is not object.__init__:
args, kw = object.__getattribute__(self, '_local__args')
cls.__init__(self, *args, **kw)
else:
object.__setattr__(self, '__dict__', d) class local(_localbase): def __getattribute__(self, name):
lock = object.__getattribute__(self, '_local__lock')
lock.acquire()
try:
_patch(self) # 这条语句执行之后,self.__dict__ 被修改成了线程独立的一个dict
return object.__getattribute__(self, name)
finally:
lock.release()
import threading
from _threading_local import local
def test():
local_data = local()
local_data.x = 1
print 'id of local_data', id(local_data) def thread_func():
before_keys = threading.current_thread().__dict__.keys()
local_data.x = 2
after = threading.current_thread().__dict__
# print set(after.keys()) - set(before.keys())
print [(e, v) for (e, v) in after.iteritems() if e not in before_keys] t = threading.Thread(target = thread_func)
t.start()
t.join()
print('x in pre thread is %s' % local_data.x) if __name__ == '__main__':
test()
输出:
id of local_data 40801456
[(('_local__key', 'thread.local.40801456'), {'x': 2})]
class GeventServer(ServerAdapter):
""" Untested. Options: * See gevent.wsgi.WSGIServer() documentation for more options.
""" def run(self, handler):
from gevent import pywsgi, local
if not isinstance(threading.local(), local.local): #注意这里
msg = "Bottle requires gevent.monkey.patch_all() (before import)"
raise RuntimeError(msg)
if self.quiet:
self.options['log'] = None
address = (self.host, self.port)
server = pywsgi.WSGIServer(address, handler, **self.options)
if 'BOTTLE_CHILD' in os.environ:
import signal
signal.signal(signal.SIGINT, lambda s, f: server.stop())
server.serve_forever()
这个小插曲其实也反映了monkey-patch的一些优势与劣势。其优势在于不对源码修改就能改变运行时行为,提高性能;同时 ,对于缺乏经验或者对patch细节不了解的人来说,会带来静态代码与运行结果之间的认知差异。
Python thread local的更多相关文章
- TLS 与 python thread local
TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming m ...
- Python - python3.7新增的contextvars vs Thread local(threading.local)
总结 和threading.local()类似.Python3.7新增. thread.local(): 不同线程,同一个变量保存不同的值. contextvars: 不同上下文,同一个变量保存不同的 ...
- [Python]threading local 线程局部变量小測试
概念 有个概念叫做线程局部变量.一般我们对多线程中的全局变量都会加锁处理,这样的变量是共享变量,每一个线程都能够读写变量,为了保持同步我们会做枷锁处理.可是有些变量初始化以后.我们仅仅想让他们在每一个 ...
- Java进阶(七)正确理解Thread Local的原理与适用场景
原创文章,始自发作者个人博客,转载请务必将下面这段话置于文章开头处(保留超链接). 本文转发自技术世界,原文链接 http://www.jasongj.com/java/threadlocal/ Th ...
- 线程TLAB局部缓存区域(Thread Local Allocation Buffer)
TLAB(Thread Local Allocation Buffer) 1,堆是JVM中所有线程共享的,因此在其上进行对象内存的分配均需要进行加锁,这也导致了new对象的开销是比较大的 2,Sun ...
- Java Thread Local – How to use and code sample(转)
转载自:https://veerasundar.com/blog/2010/11/java-thread-local-how-to-use-and-code-sample/ Thread Local ...
- Python Thread related
1.Thread.join([timeout]) Wait until the thread terminates. This blocks the calling thread until the ...
- python thread的join方法解释
python的Thread类中提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行.这个方法还可以设定一个timeout参数,避免无休止的等待.因为两个线程顺序完成,看起来象一个 ...
- 【Python@Thread】queue模块-生产者消费者问题
python通过queue模块来提供线程间的通信机制,从而可以让线程分项数据. 个人感觉queue就是管程的概念 一个生产者消费者问题 from random import randint from ...
随机推荐
- php 中文切割字符串长度
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) { if(function_ex ...
- js数组之迭代方法
ES5为数组对象定义了5个迭代方法(即递归,简单的说就是自己可以调用自己). 每个方法接收两个参数:要在每一项上运行的函数(接收3个参数:数组项的值,该项在数组中的位置,数组对象本身)和(可选的) ...
- 【spoj7528】 Lexicographical Substring Search
http://www.spoj.com/problems/SUBLEX/ (题目链接) 题意 给出一个字符串,询问其中字典序第K小的子串. Solution 后缀自动机例题. 构出后缀自动机以后,对每 ...
- Servlet_ResponseHeader
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExcepti ...
- 【uoj57】 WC2013—平面图
http://uoj.ac/problem/57 (题目链接) 题意 给出二位平面上n个点,点之间有一些连线,连线不在顶点之外的地方相交,将平面分为若干个区域.给出一些询问点对,问从这个点所在的区域走 ...
- STM32精确延迟1us和1ms的函数
STM32精确延迟1us和1ms的函数 延迟1us: /************************************************************************ ...
- 51NOD 1639 绑鞋带 数学
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1639 假如一开始有一根绳子. 那么增加一根的时候,可以插在它的尾部,也可 ...
- 微信网页授权redirect_uri错误的可能错误之一
授权回调页面域名 后面不要加/ 加了/ 就会出错.
- zepto callback
// Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT licens ...
- cpsr当前程序状态寄存器
详解CPSR寄存器(ls_core) (2012-10-11 17:29:47) 转载▼ 标签: arm920t寄存器 cpsr cpu工作原理 分类: 第四章-踏入嵌入式领域之ARM 在介绍CPSR ...