Local variables in the python thread threadlocal

Source: Internet
Author: User

It is better for a thread to use its own local variables than to use global variables.
Local variables can only be seen by the thread themselves and will not affect other threads
Changes to global variables must be locked

ThreadLocal Thread Local Variables

Import threading

# Create a global threadlocal object:
Local_school = Threading.local ()

Def process_student ():
# Gets the student associated with the current thread:
std = local_school.student
Print (' Hello,%s (in%s) '% (Std, Threading.current_thread (). Name))

def process_thread (name):
# bind Threadlocal's student:
Local_school.student = Name
Process_student ()


T1 = Threading. Thread (target= process_thread, args= (' Alice ',), name= ' thread-a ')
T2 = Threading. Thread (target= process_thread, args= (' Bob ',), name= ' Thread-b ')
T1.start ()
T2.start ()
T1.join ()
T2.join ()

Execution Result:

Hello, Alice (in thread-a)
Hello, Bob (in Thread-b)


The global variable Local_school is a Threadlocal object,
Each thread can read and write student properties to it, but it does not affect each other.

You can think of Local_school as a global variable,
But each attribute, such as local_school.student, is a thread's local variable that can be read and written without interfering


Can be understood as a global variable local_school is a dict, not only can use Local_school.student, can also bind other variables, such as local_school.teacher, etc.

Threadlocal solves the problem of passing arguments between functions in a thread.

Local variables in the python thread threadlocal

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.