线程里的全局变量threading.local

妙音 posted @ 2014年1月09日 17:09 in 并发 with tags python , 3339 阅读
通常情况下,子线程可以访问主线程中的变量,并且可以修改它。
如果线程希望有自己的变量,不允许其它线程修改。这种情况怎么办?
利用threading.local模块就可以解决这种问题。
#encoding=utf-8
from threading import local, Thread, currentThread

threadeddict = local()
threadeddict.name = "main"

ctx = {"username": "abc"}


class LocalThread(Thread):
    def run(self):
        print "-----local-------"
        print currentThread()
        print threadeddict.__dict__   # 可以访问到主线程中的变量,但是访问不了它的内容
        print ctx                     # 变量和内容都可以访问
        threadeddict.name = self.getName()  # 改变值不会影响主线程
        print threadeddict.__dict__

if __name__ == '__main__':
    print "-----main-------"
    print currentThread()
    print threadeddict.__dict__

    A = LocalThread()
    A.start()
    A.join()

    print "-----main-------"
    print currentThread()
    print threadeddict.__dict__
 
ctx变量对子线程而言有两个特征:
1.全局的(子线程内部都可访问)
2.可以访问修改的
 
threadeddict对子线程而言只有一个特征:全局的。只剩下一个全局变量名。
 

 

Avatar_small
Imamia Quran Academy 说:
2023年8月22日 08:12

The contents of the article are very original. Thanks for the work, may be a inspires for everything. I am from Imamia Quran Academy. These online Shia Quran Courses of Shia Quran Academy include basic learning of Yassarnal Quran which will make it easy for them to learn Quran and recite Holy Quran with correct Tajweed.

Avatar_small
Imamia Quran Academy 说:
2023年8月22日 08:13

Thanks for a very interesting blog. Your blog provided us with valuable information to work with. I am from Imamia Quran Academy. Learning Online Shia Yassarnal Quran in your most suitable environment under the supervision of the finest Shia Quran Teachers in your most suited hours was a dream.

Avatar_small
Imamia Quran Academy 说:
2023年8月22日 08:16

You have performed a great job on this article.  It’s very precise and highly qualitative. Thank you so much. I am from Imamia Quran Academy. The innovative technique of conducting Shia Tajweed Quran Online classes is impressive.

 

Avatar_small
Imamia Quran Academy 说:
2023年8月22日 08:18

Very nice article, I enjoyed reading your post, very nice share, I want to twit this to my followers. Thanks. I am from Imamia Quran Academy. The Online Shia Quran Classes were held virtually through platforms such as Skype, Google Meet, Zoom, Microsoft Teams, etc. Please join our Platform for learning Online Quran.

Avatar_small
meidir 说:
2023年8月22日 22:12

The great things about African Mangoo means very much to us. 插花班

Avatar_small
seo service UK 说:
2024年2月21日 20:54

Instantly this web site will irrefutably frequently end up being notable regarding all weblog consumers, due to diligent reviews as well as checks


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter