Chapter 42 of the official Python column, students stop. Don't miss this article starting from 0!
The previous two articles introduced the concept of thread and the code demonstration of multithreaded programs, but in multithreaded programs, they print independently of each other, but the time is disordered!
As shown in the following figure, t-0 > t-1 > T-2 (arranged according to the time of thread creation). The final output is actually t-1, which is the most backward.
What can we do to avoid confusion? Let's see.
Thread synchronization
Multithreading means that multiple independent running units perform the same thing at the same time.
Isn't multithreading executed at the same time? What else do you need to synchronize?
Yes, threads are called and executed at the same time, but each thread is independent and competitive with each other.
This is similar to three athletes on the track who start at the same time after the gun is fired, but they usually don't reach the finish line at the same time.
What does synchronization mean?
Synchronization is the original three people running on this runway. After synchronization, only one person is on the runway at any time.
Doesn't that sound ridiculous? How can multithreading improve efficiency for multiple tasks? Adding synchronization means that only one task can be executed at a time. What's more, multithreading.
Unfortunately, this is what synchronization means. We sometimes say that synchronization is complete and mutually exclusive! To sum up, synchronization is a mechanism that ensures that there is only one athlete on the track at any time. Technically, synchronization ensures that program data is operated by only one thread at any time.
When we use the synchronization mechanism, we are also looking for the 'track' that should be limited. We use the synchronization mechanism to ensure that only one 'athlete' runs on that track at any time.
(the explanation is very clear. If you can't understand it, you can ask your classmates to discuss the above sentences)
Now that we understand the synchronization mechanism, let's look at the lock.
threading.Lock get sync lock
threading.Lock is a class that we can use to create a lock object.
What is a lock?
Media maintaining synchronous mutual exclusion mechanism
It is equivalent to that there is a gate on the runway. Only one programmer can run in each time
Wrong, athlete (programmers still need more exercise).
If the lock is broken, the consequences can be imagined (the article will say later).
The following code will use the two Lock functions:
Acquire function: acquire lock
Release function: release lock
As mentioned earlier, plus the main thread, there are four threads in total.
Run the following code to see:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time: 12:02 am, November 21, 2021 # @Author : LeiXueWei # @CSDN/Juejin/Wechat: Thunder Science Committee # @XueWeiTag: CodingDemo # @File : __init__.py.py # @Project : hello import threading import datetime import time def dianzan_guanzhu(lock: threading.Lock): thread_name = threading.current_thread().getName() print("Thread started:", thread_name) now = datetime.datetime.now() name = "python Meng Xin" + thread_name lock.acquire() print("%s - %s name:%s" % (thread_name, now, name)) time.sleep(1) result = "Great!" + name + " Pay attention to the mine science committee,Learned to develop knowledge!" print("%s - %s result:%s" % (thread_name, now, result)) lock.release() return result my_lock = threading.Lock() for i in range(3): mythread = threading.Thread(name="t-" + str(i), target=lambda: dianzan_guanzhu(my_lock)) print("mythread:", mythread) print("is_alive:", mythread.is_alive()) mythread.start() ac = threading.active_count() print("active_count:", ac)
Here are the results:
We can see that each thread has completed the task completely, and there will be no disordered output of three threads interspersed with each other.
Here beginners can feel the role and effect of synchronization.
Summary extension
The above is a thread coordination scheme.
Thread synchronization is not the same step, but synchronization and mutual exclusion!
The school committee also mentioned that synchronization and multithreading are contradictory. Let's continue later.
Here is a small question:
How to t-0 output other functions like activate after the first line in the function is output_ Account and other information?
By the way, some students often forget to pay attention to the articles of the school committee. Don't miss many articles.
In addition, if you like Python, please pay attention to the report of the school committee Python foundation column or Introduction to Python to master the big column
Continuous learning and continuous development, I'm Lei Xuewei!
Programming is very interesting. The key is to understand the technology thoroughly.
Welcome to wechat, like and support collection!