Python Learning Notes (29) ThreadLocal

Source: Internet
Author: User

ImportThreading#To create a global threadlocal object:Local_school =threading.local ()defprocess_student ():#gets the student associated with the current thread:std =local_school.studentPrint('Hello,%s (in%s)'%(Std, Threading.current_thread (). Name))defProcess_thread (name):#binding the threadlocal student:Local_school.student =name Process_student () T1= Threading. Thread (Target=process_thread, args= ('Douzi',), name='thread-a') T2= Threading. Thread (Target=process_thread, args= ('Douzi2',), name='Thread-b') T1.start () T2.start () T1.join () T2.join ()
Hello, Douzi (in thread-a) Hello, Douzi2 (in Thread-b)

  

A global variable local_school is an ThreadLocal object , each Thread of which can read student and write properties, but does not affect each other. You can think of it local_school as a global variable, but each property, such as local_school.student a thread's local variable, can read and write without interfering with each other, and does not have to manage the lock problem, which is ThreadLocal handled internally.

Can be understood as a global variable local_school is one dict , not only can be used local_school.student , you can also bind other variables, such as local_school.teacher and so on.

ThreadLocalThe most common place is to bind a database connection for each thread, HTTP requests, user identity information , and so on, so that all the calls to the processing functions of a thread can be easily accessed by these resources .

Python Learning Notes (29) ThreadLocal

Related Article

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.