Python multithreaded Programming (iv): Using lock Mutex _python

Source: Internet
Author: User
Tags mutex in python

Python has been demonstrated earlier: using the threading module to implement multithreaded programming 22 ways to thread and Python: Using the Threading module to implement multithreaded programming the important functions of the three Threading.thread classes, both of which demonstrate an unrelated independent thread, now we Consider the question: suppose that each thread needs to access the same common resource, how should our code be written?

Copy 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 200 threads, but these 200 threads will go to 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 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

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

Mutual exclusion Lock Concept

In Python programming, the concept of object mutex is introduced to ensure the integrity of the shared data operation. Each object corresponds to a token 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 are correcting the above procedure, for which we need to add a mutex variable mutex = threading. Lock (), and then we will preempt this lock Mutex.acquire () before competing for resources, and we are releasing this lock Mutex.release () after the resource is used. The code is as follows:

Copy 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 ()

Sync blocking

This lock enters the "locked" state when a thread calls the lock object's acquire () method to acquire the locks. Because only one thread at a time can get the lock at 1, if another thread 2 attempts to acquire the lock, the thread 2 becomes the Blo sync blocking state. The lock enters the "unlocked" state after the lock is released by the release () method that owns the lock in thread 1 that calls the lock. The thread scheduler selects one of the threads in the synchronized blocking state to obtain the lock and causes the thread to enter the running (running) state.

Further consider

By using a mutex for public resources, this simply arrives at our goal, but if we are experiencing the following:

What to do when you encounter a lock nesting, which means that when I get a critical resource, a thread needs to get it again;
If there are more than one common resource, when the threads share multiple resources, if two of them have a portion of the resources and wait for each other's resources;

These two situations will directly cause the program hangs, that is, the deadlock, the following we talk about deadlock and can be rlock 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.