"Python Journey" sixth (iv): Python multi-line lock

Source: Internet
Author: User


in the process of multithreaded program execution, why do you need to give some thread Cheng and how to lock, say the following.


1. The reason for the line Cheng

We know that the memory space between different processes can not be shared, imagine, if you can freely share, talk about what security? However, multiple threads in a process can share data in the memory space of the process, for example, multiple threads can invoke some data in a memory space at the same time (just calls, without modification).

Imagine that in a process, the memory space contains a variable object value of Num=8, if there is a time when multiple threads need to use this object at the same time, in order for these threads to realize the needs of different functions, thread A needs to subtract Num 1 before use, thread B needs num plus 1 before use, Thread C is required to use NUM's original value of 8. Since these three threads are all memory spaces that share the NUM value, and these three threads can be executed concurrently, when three threads are simultaneously working on NUM, because NUM has only one, there must be a different sequence of operations, so imagine the following procedure:

Step one: Thread a modifies the value of NUM to 7 the second step: thread C does not know that Num's value has changed and calls the value of NUM 7 The third step: thread B adds 1 to the NUM value, and the NUM value becomes 8 fourth step: thread B uses num value 8 Fifth step: Thread A uses NUM value 8

Since NUM has only one, and three operations are for one NUM, the above procedure is entirely possible, and the original threads A, B, C want to use the NUM value should be: 7, 9, 8, here has become: 8, 8, 7. Imagine what the consequences would be if the operations of the three threads were critical to the execution of the entire program.

Therefore, for the sake of stable program operation, we need to Cheng the thread when we need to call the shared data in memory.


2.Python Multi-wire lock

(1)

Let's look at the following program code that does not give a line Cheng:

Import Threadingimport Timenumber = 0def run (num): global Numbernumber + = 1print numbertime.sleep (1) for I in range: t = Threading. Thread (Target=run, args= (i,)) T.start ()

The results of the program execution are as follows:

[Email protected]:/mnt/hgfs/python/day6$ Python thread_clock6.py 1234567891011121314151617181920

Above is an example of multiple threads seizing the same memory space at the same time , but from the execution results can be seen, the program is still sequentially output 1-19, and did not appear above the situation, it is only because of the small amount of reasons, although the implementation of normal, no error, but does not mean that there is no error.


(2)

Look at the code for the line Cheng below:

Import Threadingimport timenumber = 0lock = Threading. Rlock () #调用threading模块中的RLock () def run (num): Lock.acquire () #开始给线程加锁global Numbernumber + = 1lock.release () #给线 Threads Unlocked Print Numbertime.sleep (1) for I in range: T = Threading. Thread (Target=run, args= (i,)) T.start ()

The results of the program execution are as follows:

[Email protected]:/mnt/hgfs/python/day6$ Python thread_clock6.py 1234567891011121314151617181920

The execution of the program will certainly be normal, and before the line Cheng, it may be normal, note that this is two completely different concepts.

Analysis of the above program: in a thread to modify the value of NUM, which is to give the line loads lock, the line Cheng, as long as the thread needs to call the code and the memory involved in the space, will be locked immediately, such as the "Number+=1", the other threads while concurrently executing concurrently, But can not execute "number+=1" This line of code, that is not able to access or modify num this shared memory space of data, can only wait for the line threads unlocked to execute, when the line threads unlocked, another thread immediately lock and then to modify the value of number, but also do not allow other threads to occupy, And so on, until all threads have finished executing.

Based on the above analysis, the thread Cheng can be used to solve the previously mentioned threading security problem.


(3)

To better understand a process of line Cheng, modify the above code to read as follows:

Import Threadingimport timenumber = 0lock = Threading. Rlock () def run (num): Lock.acquire () global Numbernumber + = 1print numbertime.sleep (1) #把time. Sleep (1) Also lock in thread lock.release () for I in range: T = Threading. Thread (Target=run, args= (i,)) T.start ()

The results of the implementation are as follows:

[Email protected]:/mnt/hgfs/python/day6$ Python thread_clock6.py 1234567891011121314151617181920

The execution of the program is exactly the same as above, but the execution of the program is very different, here is the procedure to modify the code after the execution of the program: each output a number, sleep 1 seconds after the next number output, and so on.

For a better explanation, we can look at the time it takes to execute this program:

[Email protected]:/mnt/hgfs/python/day6$ time Python thread_clock6.py | grep ' real ' real0m20.073suser0m0.024ssys0m0.008s

The execution time can better explain the above execution process, but why? Here's an analysis: the Analysis by (2) shows that while 20 threads are concurrently executing the Run function, this differs from (2) in that (2) only locks the program code that involves modifying number, and here is the whole function locked! So when 20 threads start concurrently executing this function, the execution of each thread is locked, and the whole function is locked, so other threads cannot invoke the program code in the function, only wait for a thread to execute before calling the function's program code. The execution of a thread requires sleep (1) at a time, then the execution of 20 threads requires sleep (1) 20 times, and the process is serial, so we see the procedure as described above, it is also clear to know why the execution of the program requires 20s.



From the above analysis, we can not only know why to give the line Cheng and how to lock, but also more clearly know the line Cheng a process, and later in the writing process, similar situation, we should be for the line Cheng.

This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1701920

"Python Journey" sixth (iv): Python multi-line lock

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.