zoukankan      html  css  js  c++  java
  • 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值  时自动执行

      结果为:

  • 相关阅读:
    设计模式
    Junit单元测试
    数组存储和链表存储
    java新特型
    List&&Set
    Map
    File文件
    1588. 所有奇数长度子数组的和
    2秒后跳转到某页面
    图片轮播/倒计时--windows对象(setInterval)
  • 原文地址:https://www.cnblogs.com/sc-1067178406/p/10697029.html
Copyright © 2011-2022 走看看