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