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

  threading_namespace = threading.local()

 

python 多线程笔记(3)-- 线程的私有命名空间
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()
python 多线程笔记(3)-- 线程的私有命名空间

 

语句

  threading_namespace = threading.local()

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

 

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

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

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

 

python 多线程笔记(3)-- 线程的私有命名空间

本文转自罗兵博客园博客,原文链接:http://www.cnblogs.com/hhh5460/p/5178420.html,如需转载请自行联系原作者

相关文章:

  • 2021-06-01
  • 2021-05-23
  • 2021-04-08
  • 2022-12-23
  • 2021-08-10
  • 2021-11-28
  • 2021-06-06
  • 2021-12-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
  • 2022-01-19
  • 2021-07-12
  • 2022-02-16
相关资源
相似解决方案