Python Thread Lock

Source: Internet
Author: User

1. Thread is the smallest control unit of the application

Import Threading Import  = tendef  F ():    Global  NUM    -= 1    time.sleep (2 )    print  (NUM) for in range (5):    = Threading. Thread (target=f)    T.start ()

Execution Result:

55555

Here we create 5 threads, each of which begins to operate on Num at the end of the program, and Time.sleep (2) blocks the execution of the process, causing the process to switch, so after 2 seconds of waiting, all the threads perform the-1 operation, And finally, it prints out the final result. 5. Because a thread is a resource that shares a process, it is necessary to lock the thread when the data access between the threads crosses.

Import Threading Import  = ten= Threading. Rlock ()def  F ():    Global  NUM    lock.acquire ()    -= 1     Time.sleep (2)    lock.release ()    print  (NUM) for  in range (5):    = Threading. Thread (target=f)    T.start ()

Execution Result:

98765

There are two ways of locking, one is threading. Lock (), and another is threading. Rlock (), the latter way can be nested in the lock inside the lock, we default to use the latter way more, compatible with the front lock () lock.

Python Thread Lock

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.