Python Thread Local usage

Source: Internet
Author: User

Multi-threaded concurrency in Python, like other languages, takes into account the problems caused by multi-threaded concurrent access to global variables, and the Python local class solves this problem by letting each thread have a relatively independent local hold of the data, one thread modifying the data, Does not affect data that is saved in other threads.

1  fromThreadingImportThread2 ImportThreading3 Import Time4Local_value=threading.local ()5local_value.x='en'6 classthreadtest (Thread):7 8      def __init__(self,num):9Thread.__init__(self)Tenself.num=Num One           A      defRun (self): -local_value.x=Self.getname () -           forIinchRange (self.num): theTime.sleep (1) -              Print(Local_value) -           -  +ThreadTest (3). Start () -ThreadTest (2). Start ()

The execution results are:

Thread-1Thread-2thread-1thread-2thread-1 in 3.2s]

This shows that although two threads are common to a local_value.x but are really independent of each other variable.

In addition, when

local_value.x=Self.getname () is placed in __init__ (), the run will error, saying ' _thread._local ' object has no attribute ' x ', do not know what the problem, But let's go to dinner first.

Python Thread Local usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.