zoukankan      html  css  js  c++  java
  • threading.local之数据存储隔离

    通过Threading的local实现的本地存储隔离

    '''
    
    当我们开启多线程来执行func函数,通过自定义的Foo类来存储数据时,我们发现最终的输出结果是全部的线程打印的都是一个最终的数字10,这是因为这样存储的数据线程之间是共享
    的,当最后一个线程执行func函数时,由于func函数time.sleep了1秒钟,        
    第一个线程还没有来得及打印数据呢,就被最后一个线程传的参数给覆盖了,从而线程们打印的结果都是相同的
    
    '''
    
    import threading
    import time
    
    
    class Foo(object):
        pass
    
    
    def func(num):
        Foo.num = num
        time.sleep(1)
        print(Foo.num, threading.current_thread().ident)
    
    
    for i in range(1, 11):
        th = threading.Thread(target=func, args=(i,))
        th.start()
    
    结果
    10 35148
    10 33584
    10 31000
    10 34092
    10 29248
    10 32892
    10 30920
    10 35180
    10 33980
    10 35188
    

    flask上下文管理之threading.local

    '''
    
    我们使用Threading中的local来存储数据就可以做到数据在线程之间数据隔离。从而就可以理解为什么flask的上下文管理是基于local来实现的数据存储了。
    
    '''
    from threading import local
    import threading
    import time
    
    foo = local()
    
    
    def func(num):
        foo.num = num
        time.sleep(1)
        print(foo.num, threading.current_thread().ident)
    
    
    for i in range(1, 11):
        th = threading.Thread(target=func, args=(i,))
        th.start()
    结果
    2 35340
    1 28220
    6 35628
    7 29948
    4 35824
    5 31792
    3 34848
    10 35632
    9 28236
    8 35068
    希望你眼眸有星辰,心中有山海,从此以梦为马,不负韶华
  • 相关阅读:
    Linux下安装软件遇见的问题汇总
    使用AlarmManager定期执行工作
    android打开文件、保存对话框、创建新文件夹对话框(转载)
    一些算法的整理
    安卓adb调试命令常见的问题
    java下的串口通信-RXTX
    Unity 协程运行时的监控和优化
    Unity3D 协程的介绍和使用
    游戏服务器:到底使用UDP还是TCP
    Unity 可重复随机数
  • 原文地址:https://www.cnblogs.com/daviddd/p/11914606.html
Copyright © 2011-2022 走看看