zoukankan      html  css  js  c++  java
  • threading.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()

    上述代码实现了线程间的隔离,为每个线程开辟了独立的空间,这就是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(2)
    
        print(DIC[ident]['xxxxx'],i)
    
    for i in range(10):
        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(2)
    
        print(DIC[ident]['xxxxx'],i)
    
    for i in range(10):
        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(2)
        print(obj.xxxxx,i)
    
    for i in range(10):
        t = threading.Thread(target=task,args=(i,))
        t.start()

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

  • 相关阅读:
    Ext简单demo示例
    git命令行操作
    js继承方式
    一次活动总结
    h5自定义audio(问题及解决)
    JavaScript标准参考教材(alpha)--笔记
    css揭秘--笔记(未完)
    css权威指南--笔记
    h5上传图片及预览
    gulp入门小记
  • 原文地址:https://www.cnblogs.com/miaoweiye/p/11979043.html
Copyright © 2011-2022 走看看