Python multithreaded Programming (iv): using lock Mutex

Source: Internet
Author: User
Python is shown earlier: Multithreaded programming using the Threading Module 22 ways to start threading and Python: Using the Threading module for multithreaded programming, the important functions of the three Threading.thread classes, both of which illustrate independent threads that are unrelated to each other, and now we Consider the question: what should our code say if each thread needs access to the same public resource?

Copy the Code code as follows:


'''
Created on 2012-9-8

@author: walfred
@module: Thread. ThreadTest3
'''
Import threading
Import time

Counter = 0

Class MyThread (threading. Thread):
def __init__ (self):
Threading. Thread.__init__ (self)

def run (self):
Global Counter
Time.sleep (1);
Counter + = 1
Print "I am%s, set counter:%s"% (self.name, counter)

if __name__ = = "__main__":
For I in range (0, 200):
My_thread = MyThread ()
My_thread.start ()

To solve the above problem, we might write this code, we assume that running 200 threads, but the 200 threads will go to access counter this public resource, and the resource processing (counter + = 1), the code looks like this, but we look at the results of the operation:
Copy the Code code as follows:


I am Thread-69, set counter:64
I am Thread-73, set counter:66i am Thread-74, set counter:67i am Thread-75, set counter:68i am Thread-76, set counter:69i Am Thread-78, set counter:70i am Thread-77, set counter:71i am Thread-58, set counter:72i am Thread-60, set counter:73i am Thread-62, set counter:74i am thread-66,set counter:75i am Thread-70, set counter:76i am Thread-72, set counter:77i am Th read-79, set counter:78i am Thread-71, set counter:78


Printing results I only posted a part, from which we have seen that the global resource (counter) is preempted, the problem is caused by not controlling the access of multiple threads to the same resource, causing damage to the data, so that the results of the thread run is not predictable. This behavior is called "Thread insecurity." In the development process we have to avoid this situation, how to avoid it? This uses the mutex we mentioned in the review.

The concept of Mutex lock

In Python programming, the concept of object mutexes is introduced to ensure the integrity of shared data operations. Each object corresponds to a tag that can be called a "mutex", which is used to guarantee that only one thread can access the object at any one time. In Python we use the lock class provided by the threading module.

We have to rectify the above program, for which we need to add a mutex variable mutex = threading. Lock (), and then we will preempt this lock mutex.acquire () before we scramble for resources, and we release this lock Mutex.release () after the use of the resource is complete. The code is as follows:
Copy the Code code as follows:


'''
Created on 2012-9-8

@author: walfred
@module: Thread. ThreadTest4
'''

Import threading
Import time

Counter = 0
Mutex = Threading. Lock ()

Class MyThread (threading. Thread):
def __init__ (self):
Threading. Thread.__init__ (self)

def run (self):
Global Counter, Mutex
Time.sleep (1);
If Mutex.acquire ():
Counter + = 1
Print "I am%s, set counter:%s"% (self.name, counter)
Mutex.release ()

if __name__ = = "__main__":
For I in range (0, 100):
My_thread = MyThread ()
My_thread.start ()

Synchronous blocking

When a thread calls the lock object's acquire () method to obtain the locks, the lock enters the "locked" state. Because only one thread 1 can acquire a lock at a time, if another thread 2 attempts to acquire the lock at this point, the thread 2 becomes "blo synchronous blocking state." The lock enters the "unlocked" state until the lock is released by the release () method that has the lock's thread 1 call lock. The thread scheduler chooses one of the threads in the synchronous blocking state to obtain the lock and causes the thread to enter the running (running) state.

Further consideration

By using mutual exclusion locks on public resources, it is easy to reach our goal, but if we encounter the following situation:

What to do if a lock nesting is encountered, this nesting means that when I get a thread in the critical resource, I need to get it again;
If there are multiple public resources, when the thread shares multiple resources, if two threads occupy a portion of the resources and wait for each other's resources at the same time;

These two situations will directly cause the program to hang, that is, deadlock, below we talk about deadlock and can be re-entry lock Rlock.

  • 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.