The concept of Python lock in multi-threading

Source: Internet
Author: User

Python's locks can be extracted independently.

Mutex = Threading. Lock () #锁的使用 # Create Lock Mutex = Threading. Lock () #锁定mutex. Acquire ([timeout]) #释放mutex. Release ()

Concept

Several people asked me how to lock the resources, in fact, not to lock resources, but to lock the resources, you can define multiple locks, like the following code, when you need to monopolize a resource, any lock can lock the resource

It's like you can lock the same one with different locks.

import Threading Import Time counter = 0 Counter_lock = Threading. Lock () #只是定义一个锁, not to lock the resources, you can define multiple locks, like the next two lines of code, when you need to occupy this resource, any lock can lock this resource Counter_lock2 = threading. Lock () Counter_lock3 = Threading. Lock () #可以使用上边三个锁的任何一个来锁定资源 class MyThread (threading. Thread): #使用类定义thread, inherit threading. Thread def __init__ (self,name): Threading. Thread.__init__ (self) self.name = "thread-" + str (name) def run (self): #run函数必须实现 Global Coun             Ter,counter_lock #多线程是共享资源的, use global variable time.sleep (1);                 If Counter_lock.acquire (): #当需要独占counter资源时, it must be locked, this lock can be any one lock, you can use the above definition of any one of the 3 locks counter + = 1 Print "I am%s, set counter:%s"% (self.name,counter) counter_lock.release () #使用完counter资源必须要将这个锁打开, let other lines          Process using if __name__ = = "__main__": For I in Xrange (1,101): My_thread = MyThread (i) My_thread.start ()  

Thread is not secure:

One of the most common multithreaded small examples. I took a piece of the story, and I created a subclass mythread that inherits the thread class as our thread startup class. As a rule, rewrite the thread's Run method, which is called automatically when our thread starts up. So I first created 10 threads and added them to the list. Then use a For loop to turn on each thread. When using a For loop, call the Join method to wait for all threads to end before exiting the main thread.

This code may seem simple, but it actually hides a big problem, but it doesn't show up here. You really think I created 10 threads and sequentially called the 10 threads, and each thread added 1 to N. In fact, it is possible that a thread executes the n++, then the C thread executes the n++, and the B thread executes n++.

This involves a "lock" problem, if there are multiple threads operating an object at the same time, if the object is not well protected, it will cause the program results unpredictable (for example, we add a time.sleep (1) to the Run method of each thread, and output the thread name at the same time, Then we'll find out that the output will be messy. Because it is possible that one of our print statements prints only half the characters, the thread is paused and executes the other, so we see a messy result, which is called "thread unsafe".

Thread Lock:

so , the threading module provides us with a class, Threading.lock, lock. We create a class object, before the thread function executes, "preempt" the lock, after execution completes, "releases" the lock, we ensure that only one thread occupies the lock at a time. When you operate on a common object, there is no thread-insecure behavior.

So, we changed the code as follows:

# coding:uft-8__author__ = ' phtih0n ' import threading, Timeclass 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, $):        t = MyThread ()        threadlist.append (t) for    T in Threadlist:        T.start () for    T in Threadlist:        t.join ()
1 Thread-22 Thread-33 Thread-44 Thread-65 Thread-76 Thread-17 Thread-88 Thread-99 thread-5process finished with exit code 0

  

We see that we first set up a threading. Lock class object lock, in the Run method, we use Lock.acquire () to obtain this lock. At this point, the other threads will no longer be able to acquire the lock, and they will block the "if Lock.acquire ()" Here until the lock is freed by another thread: Lock.release ().

So, the content in the IF statement is a complete piece of code, and there is no longer a case of pausing to execute another thread in half execution. So the final result is neat.

Just as in Java, we use the Synchronized keyword to decorate a method that, in the same way, allows a piece of code to be executed by one thread without interrupting the jump to another thread.

This is the case when multithreading consumes a common object. If multiple threads are to invoke multiple phenomena, and a thread calls a lock to occupy the A object, B thread calls the B lock takes up the B object, a thread cannot invoke the B object, B thread cannot invoke the A object, and so waits. This creates a thread "deadlock".

In the threading module, there is also a class, Rlock, which is called a reentrant lock. The lock object is internally maintained with a lock and a counter object. The Counter object records the number of acquire, so that resources can be require multiple times. Finally, when all Rlock are release, other threads can get the resources. In the same thread, Rlock.acquire can be called multiple times, using this feature to resolve partial deadlock problems.

  

The concept of Python lock in multi-threading

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.