directory

  • A preface.
  • Python threads share global variables
  • Python thread mutex
    • 1. Create a mutex
    • 2. Lock or unlock resources
  • Python thread deadlocks
  • Five. Key summary
  • Six. Guess you like it

A preface.

In Python thread creation and parameter passing, we introduced some simple functions for Python threads and parameter passing. Using multiple threads can perform multiple tasks at the same time and improve development efficiency. However, in practical development, we often encounter thread synchronization problems. To increase efficiency, we can use multi-threading to complete the sum of global variables 1,000,000 times. The sample code is as follows:

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python thread mutex lock. py @time :2021/04/22 08:00 @motto: A thousand miles without a small step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! Def my_thread1() = 0 def my_thread1(): G_num = g_num + 1 def my_thread2(): G_num = g_num + 1 def main(I): G_num = 0 g_num = 0 T1 = threading.thread (target=my_thread1) t2 = threading.thread (target=my_thread2) # threading.thread.start () t2 = threading.thread.start () T2. The start () # blocking function, waiting for the thread end of t1. The join () t2. Join (#) to obtain the value of the global variable print (" the first calculate results: % d % d "% (I, g_num)) if __name__ = =" __main__ ": For I in range(1,5): Output result: first calculation result: 1262996 Second calculation result: 1661455 Third calculation result: 1300211 fourth calculation result: 1563699 ""Copy the code

what ? What operation is this? The code looks fine. Shouldn’t two threads, each adding 1,000,000 times, output 2,000,000 times? The main function is called 4 times and the output is different each time!!

Python threads share global variables

Analyze the above code: Two threads share a global variable and execute the for loop 1000000, incrementing each time by 1. We know that both threads are running at the same time. It looks like it’s still going to be 2 million, right?

First, we split the code above for automatically incrementing the global variable into two steps:

Step 2: Assign the result of g_num + 1 to g_numCopy the code

Therefore, the implementation of a full automatic plus 1 for up to two steps, but the thread is running at the same time, no one can guarantee thread one of the first step and second step completed the first step in the execution thread 2 and the second step, the process of execution is full of randomness, that is the cause of each calculation results of different!

Here’s a simple example:

If the value of g_num is 100, and thread 1 performs the first step, the CPU computs the result 101, and is about to assign the result 101 to g_num, then thread 2 suddenly starts executing and performs the first step. The value of g_num is still not 100,101 is still in the process of passing, and is not successfully assigned. Thread 2 has obtained the result of 101, and is about to pass it to g_num. After two increments, the result of g_num is 101. Often the more loops, the greater the error.

Python thread mutex

To avoid the above problem, we can use thread mutex to solve this problem. So how does a mutex work? Mutex is like queuing to go to the toilet. Only one person can stay in a pit, and only one person can get in if the person who occupies the pit is finished!

1. Create a mutex

Import the thread module and create the mutex through threading.lock.

Mutex = threading.lock ()Copy the code

2. Lock or unlock resources

  • **acquire ** – Lock resources. At this time, resources are locked. Other threads cannot modify the locked resources until they are released.
  • Release – To release resources, also known as the unlock operation, to unlock the locked resources. After unlocking the resources, other threads can operate the resources normally.

To obtain the correct result, you can use the mutex to lock the resource before adding 1 to the global variable, and then release the resource after completing the calculation. This is a complete calculation process. . The demo code is as follows:

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python thread mutex lock. py @time :2021/04/22 08:00 @motto: A thousand miles without a small step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! Mutex = threading.lock () def my_thread1(): For I in range(0,1, 000): Def my_thread2() def my_thread2() def my_thread2() def my_thread2() def my_thread2() def my_thread2() def my_thread2() def my_thread2() def my_thread2() def my_thread2() For I in range(0,1, 000): Acquire () g_num = g_num + 1 def main(I): G_num = 0 g_num = 0 T1 = threading.thread (target=my_thread1) t2 = threading.thread (target=my_thread2) # threading.thread.start () t2 = threading.thread.start () T2. The start () # blocking function, waiting for the thread end of t1. The join () t2. Join (#) to obtain the value of the global variable print (" the first calculate results: % d % d "% (I, g_num)) if __name__ = =" __main__ ": For I in range(1,5): Output result: first calculation result: 2000000 Second calculation result: 2000000 Third calculation result: 2000000 fourth calculation result: 2000000"Copy the code

Thus, global variable evaluation with mutex is the same no matter how many times it is performed. Note: Once the mutex is locked, remember to unlock it; otherwise, the resource will remain locked.

Python thread deadlocks

1. Deadlocks of a single mutex: Acquire/release occur in pairs. After the mutex locks resources, it must be unlocked; otherwise, resources will remain locked and cannot be modified by other threads. As in the above code, any thread that does not release a resource will block (waiting for the resource to be released). Try it

2. Multiple mutex deadlock: at the same time the operation of multiple mutex must be particularly careful, because not careful is easy to enter the dead cycle, if there is such a scene: boss programmer to achieve a function of a development, let programmer two to achieve the development of two functions, functional development after the completion of the integration of the code!

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python thread mutex lock. py @time :2021/04/22 08:00 @motto: A thousand miles without a small step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! Mutex_one = threading.lock () mutex_two = threading.Lock() def programmer_thread1(): Mutex_one.acquire () print(" I am programmer 1, module1 development started, nobody touch my code ") Acquire () print(" wait for programmer 2 to tell me to merge code ") mutex_one.release() def programmer_thread2(): Mutex_two.acquire () print(" I am programmer 2, module2 development started, nobody touch my code ") Mutex_one.acquire () print(" Wait for programmer 1 to tell me to merge code ") mutex_two.release() def main(): Thread(target=programmer_thread1) t2 = threading. Thread2 (target=programmer_thread2) T1.join () t2.join() # print(" merge ") if __name__ == "__main__": Main () "" output:" I'm programmer 1, module1 development is officially started, nobody moves my code ""Copy the code

Programmer 1 is waiting for notification from programmer 2, programmer 2 is waiting for notification from programmer 1, and both threads are blocked because they are waiting for each other to unlock. This is a deadlock! So deadlocks in the development of the problem or need to pay attention to!

Five. Key summary

  • 1. The mutex must be set for sharing global variables between threads.
  • 2. Note that **acquire/release ** is paired in the mutex operation to avoid deadlock;

Six. Guess you like it

  1. The Python for loop
  2. The Python string
  3. The Python list
  4. The Python tuple tuple
  5. Python dictionary dict
  6. Python conditional derivations
  7. Python list derivations
  8. Python dictionary derivations
  9. Python function declarations and calls
  10. Python variable argument *argc/**kargcs
  11. Python anonymous function lambda
  12. Python return logic determines expressions
  13. Python string/list/tuple/dictionary conversions
  14. Python local and global variables
  15. The Python type function is different from the isinstance function
  16. Python is differs from ==
  17. Python mutable and immutable data types
  18. Shallow and deep copies of Python

Python thread mutex Lock

This article is published by the blog – Ape Say Programming Ape Say programming!