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 ...
随机推荐
- [cocos2d-x] --- CCNode类详解
Email : awodefeng@163.com 1 CCNode是cocos2d-x中一个很重要的类,CCNode是场景.层.菜单.精灵等的父类.而我们在使用cocos2d-x时,接触最多的就是场 ...
- ASP.NET脚本过滤-防止跨站脚本攻击[转]
ASP.Net 1.1后引入了对提交表单自动检查是否存在XSS(跨站脚本攻击)的能力.当用户试图用<xxxx>之类的输入影响页面返回结果的时候,ASP.Net的引擎会引发一个HttpReq ...
- Vector类
/* * Vector的特有功能 * * Vector出现较早,比集合更早出现 * * 1:添加功能 * public void addElement(Object obj);//用add()替代 * ...
- JQuery中根据表单元素动态拼接json 字符串
// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o ...
- Unity3D ——强大的跨平台3D游戏开发工具(六)
第十一章 制作炮台的旋转 大家知道,炮台需要向四周不同的角度发射炮弹,这就需要我们将炮台设置成为会旋转的物体,接下来我们就一起制作一个会旋转的炮台. 第一步:给炮台的炮筒添加旋转函数. 给炮台的炮筒部 ...
- HUSTOJ 2796 && SPOJ1811
传送门:http://begin.lydsy.com/JudgeOnline/problem.php?id=2796 题解:后缀自动机,很裸,但是感觉对后缀自动机还不是特别理解,毕竟我太蒟蒻,等我精通 ...
- 2.10. 代码片段:demo方法(Core Data 应用程序实践指南)
该代码段我觉得没有太多东西 - (void)applicationDidBecomeActive:(UIApplication *)application { [self cdh]; [self de ...
- PHP 下载远程图片
方法一:file_get_contents /**-- 下载远程文件 --**/ function down_img($url){ set_time_limit(60); if($url==" ...
- iOS 知识点
1. @dynamic.@synthesize 2. iOS NSTimer 3. iOS 之 Aggregate Target 4. iOS 属性之assign.copy.retain 5. iOS ...
- cvc-complex-type.2.4.c: The matching wildcard...
在家里的电脑好好的,在单位的就不行,需要把web app libraties提到 最前面,然后clean一下项目