zoukankan      html  css  js  c++  java
  • Threading.local

    在多线程环境下,每个线程都有自己的数据。一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁。

    Threading.local可以创建一个对象,每个线程都可以对他读写属性,但不会互相影响

    import threading
    import time
    # 创建全局ThreadLocal对象:
    class A:
        pass
    # local_school = A()
    local_school = threading.local()
    
    def process_student():
        print('Hello, %s (in %s)' % (local_school.student, threading.current_thread().name))
    
    def process_thread(name):
        # 绑定ThreadLocal的student:
    
        local_school.student = name
        time.sleep(2)
        process_student()
    a = []
    for i in range(20):
        a.append(threading.Thread(target= process_thread, args=(str(i),), name=str(i)))
    
    for i in a:
        i.start()
    

    通过字典以及面向对象中的魔法方法来自己实现一个

    import time
    from threading import get_ident,Thread
    class PPP:
        def __init__(self):
            object.__setattr__(self,"storage", {})
        def __setattr__(self, key, value):
            if get_ident() in self.storage:
                self.storage[get_ident()][key]=value
            else:
                self.storage[get_ident()] ={key: value}
        def __getattr__(self, item):
            return  self.storage[get_ident()][item]
    
    p =PPP()
    def task(arg):
        p.a = arg
        time.sleep(2)
        print(p.a)
    
    
    for i in range(10):
        t = Thread(target=task,args=(i,))
        t.start()
    

      

  • 相关阅读:
    字符编码
    IO流技术
    TreeMap使用和Comparable比较
    Collections工具类
    使用迭代器进行遍历时
    238. 除自身以外数组的乘积
    python 字典按键、值排序
    collections.Counter用法
    442. 数组中重复的数据
    1395. 统计作战单位数
  • 原文地址:https://www.cnblogs.com/wwg945/p/8921393.html
Copyright © 2011-2022 走看看