[Python journey] Article 6 (4): Python multi-thread lock

Source: Internet
Author: User

[Python journey] Article 6 (4): Python multi-thread lock
In the process of multi-threaded program execution, the following describes why some threads need to be locked and how to lock them. 1. The reason for locking a thread is that the data in the memory space between different processes cannot be shared. Imagine how safe it is to share data freely? However, multiple threads in a process can share the data in the memory space of the process. For example, multiple threads can call some data in a memory space at the same time (just call, not modified ). Imagine that in a process, the value of a variable object in the memory space is num = 8. If multiple threads need to use this object at the same time, out of the need for these threads to implement different functions, thread A needs to reduce num by 1 before use, and thread B needs to add num to 1 before use, thread C uses the original num value of 8. Because these three threads share the memory space for storing the num value, and these three threads can be concurrently executed, when the three threads operate on the num simultaneously, because there is only one num, there will certainly be different operation sequence. Imagine the operation process below the handler:

Step 1: thread A modifies the value of num to 7 Step 2: thread C does not know that the value of num has changed, and directly calls the value of num Step 7: thread B adds 1 to the num value, and the num value changes to 8 Step 4: thread B uses the num value 8 Step 5: thread A uses the num value 8

 

Because there is only one num, and all three operations are for one num, the above operation is completely possible, the original threads A, B, and C should use the following num values: 7, 9, and 8, which are changed to: 8, 8, and 7. Imagine what would happen if the operations of these three threads are crucial to the execution of the entire program? Therefore, for the stable running of the program, we need to lock the thread when the thread needs to call the shared data in the memory. 2. Python multi-threaded lock (1) first look at the following code that does not lock the thread:
import threadingimport timenumber = 0def run(num):    global number    number += 1    print number    time.sleep(1)     for i in range(20):    t = threading.Thread(target=run, args=(i,))    t.start()

 

The program execution result is as follows:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ python thread_clock6.py 1234567891011121314151617181920

 

The above example shows that multiple threads can seize the same memory space at the same time, but from the execution results, we can see that the program still outputs 1-19 in sequence without the above situation, this is only because of the small amount of data. Although the execution is normal and there is no error, it does not mean that there will be no error. (2) Check the following code for locking a thread:
Import threadingimport timenumber = 0 lock = threading. RLock () # Call RLock () def run (num) in the threading module: lock. acquire () # Start to lock the thread with global number + = 1 lock. release () # unlock print number time for the thread. sleep (1) for I in range (20): t = threading. thread (target = run, args = (I,) t. start ()

 

The program execution result is as follows:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ python thread_clock6.py 1234567891011121314151617181920

 

The execution result of the program is certainly normal, but it may be normal before the thread is locked. Note that these two concepts are completely different. Analyze the above program: When a thread modifies the num value, it locks the thread. After the thread is locked, as long as the code to be called by this thread and the memory space involved will be immediately locked, for example, "number + = 1" here, while other threads are concurrently executed, however, you cannot run the "number + = 1" line of code, that is, you cannot access or modify the data in the shared memory of num. You can only wait until the thread is unlocked; after the thread is unlocked, the other thread immediately locks the thread and then modifies the value of number, and does not allow other threads to occupy the thread, and so on until all threads have completed execution. According to the above analysis, locking the thread can solve the thread security problem mentioned above. (3) to better understand a thread lock process, modify the above Code as follows:
Import threadingimport timenumber = 0 lock = threading. RLock () def run (num): lock. acquire () global number + = 1 print number time. sleep (1) # set time. sleep (1) also locks the lock in the thread. release () for I in range (20): t = threading. thread (target = run, args = (I,) t. start ()

 

The execution result is as follows:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ python thread_clock6.py 1234567891011121314151617181920

 

The execution result of the program is the same as above, but the execution process of the program is very different. Here we will talk about the execution process of the program after the code is modified: Each number is output, sleep outputs the next number after 1 second, and so on. For better explanation, let's take a look at the time taken to execute this program:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ time python thread_clock6.py | grep 'real'real    0m20.073suser    0m0.024ssys 0m0.008s

 

The execution time can better explain the above execution process, but why? The following analysis: from the analysis of (2), we can see that although the 20 threads run the run function concurrently, the difference between this function and (2) Is that (2) only the program code that involves modifying the number is locked, and the entire function is locked here! Therefore, when 20 threads start to execute this function concurrently, the execution of each thread must be locked and the entire execution function is locked, therefore, other threads cannot call the program code in the function. They can only wait for a thread to finish executing and then call the program code of the function. In this way, the execution of a thread needs to sleep (1) once, the execution of 20 threads needs to sleep (1) 20 times, and the process is serial, so we can see the program execution process as mentioned above, you can also clearly understand why the program execution takes 20 s. From the above analysis, we can not only know why to lock the thread and how to lock it, but also clearly know the process of locking the thread. When writing a program, in a similar case, we should lock the thread.

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.