• flask --- 04 . 偏函数, 线程安全,栈堆,


    一.偏函数(partial)

      ①第一种

      结果为:

      ② 第二种

    二.线程安全

        将空间转换成时间

      问题: 1秒钟打印所有结果

    threading.current_thread().ident  :线程ID

      ①不安全示例

    import time
    from threading import Thread
    import threading
    
    
    class Foo(object):
        pass
    
    foo = Foo()
    
    def add(i):
        foo.num = i
        time.sleep(1)
        print(foo.num,i,threading.current_thread().ident,foo)
    for i in range(20): task = Thread(target=add,args=(i,)) task.start()

      结果为:

       ②线程安全 (local)

    import time
    from threading import Thread
    import threading
    
    
    
    from threading import local
    
    class Foo(local):
        pass
    
    foo = Foo()
    
    def add(i):
        foo.num = i
        time.sleep(1)
        print(foo.num,i,threading.current_thread().ident,foo)
    
    for i in range(20):
        task = Thread(target=add,args=(i,))
        task.start()

       结果为:

     三.堆栈(简化版)

    堆:
    先进先出,后进后出
    
    栈:
    先进后出,后进先出

      栈示例:

    import time
    
    # stack = [] # [request1,session1],[r2,s2],[r3,s3]
    
    from threading import local,Thread
    import threading
    
    class MyLocalStack(local):
        stack = {}
        pass
    
    
    mls = MyLocalStack()
    
    def ts(i):
        a = threading.current_thread().ident  #线程ID
        mls.stack[a] = [f"r{i+1}",f"s{i+1}"]  # 存入
        time.sleep(1)
        print(mls.stack[a].pop(),mls.stack[a].pop(),a)
    
        # time.sleep(1)
        mls.stack.pop(a)    #取出
        print(mls.stack , a)
    
    for i in range(5):
        task = Thread(target=ts,args=(i,))
        task.start()

     四. 面向对象的特殊成员

    __call__  :   对象( )  时,会自动执行

    __setattr__ :   对象.key值 = value值   时自动执行
    
    
    __getattr__  :   对象. key值  时自动执行

      结果为:

  • 相关阅读:
    疑问:关于strcmp()以及此指针表现形式*(char * *)a
    后置操作符
    php学习笔记(一)
    windows php环境配置
    关于wifi破解那点事
    C++使用大漠插件及截图
    跨平台网络编程
    reinterpret_cast, static_cast , dynamic_cast ,const_cast 的总结
    初识按键精灵
    python 程序打包-----py2exe
  • 原文地址:https://www.cnblogs.com/sc-1067178406/p/10697029.html
Copyright © 2020-2023  润新知