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

原文地址:https://www.cnblogs.com/hhh5460/p/5178420.html