Analysis on multithreading and program Lock in Python

Source: Internet
Author: User
This article mainly introduces the multi-thread and program lock analysis in Python. This article uses an example to explain the multi-thread and program Lock in Python. For more information, see the Threading module used by multiple threads in Python. The main class used in the Threading module is Thread. let's first write a simple multi-threaded code:

The code is as follows:


# Coding: uft-8
_ Author _ = 'phtih0n'
Import threading

Class MyThread (threading. Thread ):
Def _ init _ (self ):
Threading. Thread. _ init _ (self)

Def run (self ):
Global n
Print n
N + = 1

If "_ main _" = _ name __:
N = 0
ThreadList = []
For I in range (0, 10 ):
T = MyThread ()
ThreadList. append (t)
For t in ThreadList:
T. start ()
For t in ThreadList:
T. join

The most common example is multithreading. In my remarks, I created a subclass MyThread that inherits the Thread class as our Thread startup class. According to the regulations, rewrite the Thread run method, which will be automatically called after the Thread starts. So I first created 10 threads and added them to the list. Use a for loop to enable each thread. When a for loop is used, the join method is called to exit the main thread only after all threads end.

This code seems simple, but it actually hides a big problem, but it is not shown here. You really thought that I created 10 threads and called these 10 threads in order. each thread adds 1 to n. in fact, it may be that thread A executes n ++, thread C executes n ++, and thread B executes n ++.

This involves a "lock" problem. if multiple threads operate on an object at the same time, if this object is not well protected, will cause unexpected program results (for example, we add a time in the run method of each thread. sleep (1) and output the thread name at the same time, we will find that the output will be messy. Because one of our print statements may print only half of the characters, this thread will be paused and the other will be executed, so we can see a mess ), this phenomenon is called "thread unsafe ":

Therefore, the Threading module provides us with a class, Threading. Lock and Lock. We create a class object. before the thread function is executed, we "preemptible" the lock. after the execution is complete, we "release" the lock and ensure that only one thread occupies the lock at a time. At this time, operations on a public object will not cause thread insecurity.

So we changed the code as follows:

The code is as follows:


# Coding: uft-8
_ Author _ = 'phtih0n'
Import threading, time

Class MyThread (threading. Thread ):
Def _ init _ (self ):
Threading. Thread. _ init _ (self)

Def run (self ):
Global n, lock
Time. sleep (1)
If lock. acquire ():
Print n, self. name
N + = 1
Lock. release ()

If "_ main _" = _ name __:
N = 1
ThreadList = []
Lock = threading. Lock ()
For I in range (1,200 ):
T = MyThread ()
ThreadList. append (t)
For t in ThreadList:
T. start ()
For t in ThreadList:
T. join ()

Final execution result:

We can see that we first created a threading. Lock class object lock. in the run method, we obtained the lock using Lock. acquire. At this time, other threads will no longer be able to obtain the lock, and they will block the "if lock. acquire () "here until the lock is released by another thread: lock. release ().

Therefore, the content in the if statement is a complete piece of code, and the execution of other threads will not be suspended if the execution is half done. So the final result is neat.

Just as in java, we use the synchronized keyword to modify a method, so that when a code segment is executed by one thread, it will not be interrupted to jump to another thread.

This is the case when multiple threads occupy a public object. If multiple threads need to call multiple phenomena, while thread A calls lock A occupies object A, Thread B calls lock B occupies object B, and thread A cannot call object B, thread B cannot call object A, so it waits. This causes a "deadlock" on the thread ".

The Threading module also has a class, RLock, which is called reentrant lock. The Lock object maintains a Lock and a counter object. The counter object records the number of acquire times so that resources can be require multiple times. Finally, when all rlocks are release, other threads can obtain resources. In the same thread, RLock. acquire can be called multiple times. this feature can be used to solve some deadlocks.

The deadlock problem is very complicated. people have come up with many algorithms to solve it over the years. I will not talk about it more. for details, refer to the help documentation.

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.