zoukankan      html  css  js  c++  java
  • python 多线程笔记(3)-- 线程的私有命名空间

    线程的私有命名空间实现:

      threading_namespace = threading.local()

    import threading
    import time
    import random
    
    
    threading_namespace = threading.local() # 命名空间
    
    def print_country():
        thread_name = threading.current_thread().getName()
        country = threading_namespace.country      # 获取变量
        print('{}  {}'.format(thread_name, country))
    
    def my_func(country):
        threading_namespace.country = country  # 设置变量
        
        for i in range(4):
            time.sleep(random.randrange(1,7))
            print_country()
    
            
    if __name__ == '__main__':
        
        countries = ['America','China','Jappen','Russia']
        
        threads = []
        for country in countries:
            threads.append(threading.Thread(target= my_func, args=(country,)))
    
        for t in threads:
            t.start()
            
        for t in threads:
            t.join()

    语句

      threading_namespace = threading.local()

    相当于给每个线程定义了各自的命名空间

    函数 print_country() 内部对变量 country 进行了操作。

    1. 如果不用 threading.local(),那么就需要给它传入一个参数 country,不同的线程参数值不一样!

    2. 使用 threading.local() 的好处是对函数 print_country() 不需要传参,直接从命名空间 threading_namespace 去获取变量:country

  • 相关阅读:
    What is a Complex Element
    XSD(Schema)教程 [转]
    XML对WEB开发的意义
    System.Xml名称空间下的支持DOM的类型
    C#:XML操作类
    xsl:valueof select="." 什么意思?
    文档对象模型
    XSLT转换XML
    DTCMS添加栏目教程
    win8 Windows Media Player 启动后CPU占用率高(60%左右)的解决办法
  • 原文地址:https://www.cnblogs.com/hhh5460/p/5178420.html
Copyright © 2011-2022 走看看