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

  • 相关阅读:
    Linq 入门系列 [Take,Skip,TakeWhile,SkipWhile]篇
    SqlString 引发的思考
    DLINQ
    Wrf 格式播放器
    仙剑奇侠传4序列号
    Asp.Net程序性能 浅谈
    Linq 扩展函数的应用
    正则表达式积累
    ajax 之取消服务器任务[转]
    Linq 演变的过程(delegate => Lamb => Linq)
  • 原文地址:https://www.cnblogs.com/hhh5460/p/5178420.html
Copyright © 2011-2022 走看看