首页 > 编程语言 > 详细

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

时间:2016-02-02 20:39:56      阅读:212      评论:0      收藏:0      [点我收藏+]

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

  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

 

技术分享

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

原文:http://www.cnblogs.com/hhh5460/p/5178420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!