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()
    

      

  • 相关阅读:
    列表基本操作——1
    条件判断与嵌套
    数据拼接与数据转换
    变量与赋值
    打印数与type()函数
    print()函数与打印字符串
    arduino开发ESP8266学习笔记二----按键控制LED灯
    arduino开发ESP8266学习笔记一 ----点亮一个LED灯
    无线充电
    EMC设计总结
  • 原文地址:https://www.cnblogs.com/wwg945/p/8921393.html
Copyright © 2011-2022 走看看