current position：Home>Python thread 03 thread synchronization
Python thread 03 thread synchronization
2022-02-01 06:46:14 【Lei Xuewei】
「 This is my participation 11 The fourth of the yuegengwen challenge 20 God , Check out the activity details ：2021 One last more challenge 」
ceremonial Python Column No 42 piece , Classmate, stop , Don't miss this from 0 The beginning of the article ！
The previous two articles introduced the concept of threading and the code demonstration of multithreaded programs , But in multithreaded programs , They print independently of each other, but the time is chaotic ！
And clearly t-0 > t-1 > t-2 （ Sort by thread creation time ）. The final output is t-1 Most backward .
What can we do to avoid confusion , Let's see below. .
Multithreading , That's more than one. Independent operating unit , Do the same thing at the same time .
Isn't multithreading done 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 of each other , Also competing with each other .
It's like there's... On the runway 3 An athlete , After the gunshot, run at the same time , But they Usually But not at the same time .
What does synchronization mean ？
Synchronization is the synchronization of three people running on this track , At any time , There's only one person on the runway .
Doesn't that sound ridiculous , How can multithreading not improve efficiency for multiple tasks ？ Add a synchronization, not only one task is executed at a time , What else is multithreading .
unfortunately , That's what synchronization means , We sometimes say it completely , Synchronous mutual exclusion ！ In conclusion, it is ： Synchronization is a mechanism , It ensures that there is only one athlete on the track at any time . Technically, it's just , Synchronization guarantees Program data It is operated by only one thread at any time .
When we use the synchronization mechanism , Also looking for those that should be limited ’ runway ‘, The synchronization mechanism is used to ensure that there is only one... At any time on that runway ‘ Athletes ’ Run on it .
（ The explanation is very clear , If you don't understand, you can ask your classmates to discuss the above sentences ）
We understand the synchronization mechanism , Let's look at the lock .
threading.Lock Get sync lock
threading.Lock Is a class , We can use it to create a lock object .
What is a lock ？
A medium that maintains a synchronous mutual exclusion mechanism
Equivalent to a gate on the runway , Just open the door at a time and let one programmer in and run
Wrong , Athletes （ Programmers still need more exercise ）.
If the lock breaks , The consequences can be imagined （ The following article will say ）.
We will use the following code Lock Two functions of ：
acquire function ： Get the lock release function ： Release the lock
As I said before , Plus the main thread , Is the total 6 Threads .
Run the following code to see ：
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/11/21 12:02 In the morning # @Author : LeiXueWei # @CSDN/Juejin/Wechat: Lei Xuewei # @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(" The thread starts :", thread_name) now = datetime.datetime.now() name = "python Adorable new " + thread_name lock.acquire() print("%s - %s name:%s" % (thread_name, now, name)) time.sleep(1) result = " very good ！" + name + " Pay attention to Lei Xuewei , 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) Copy code
Here are the results ：
We see that each thread has completed the task completely , There will be no output of three threads interspersed with each other .
Here beginners can feel the role of synchronization , effect .
The above is a thread coordination scheme .
Thread synchronization , Not at the same pace , It's synchronous and mutually exclusive ！
The school committee also mentioned that synchronization and multithreading are contradictory , Keep looking back .
Here's a small question ：
Yes? t-0 After the first line in the output function , Other output like activate_acount Etc ？
by the way , Some students often forget to pay attention to , Don't miss a lot of articles .
Besides, I like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column
Continuous learning and continuous development , I'm Lei Xuewei ！
Programming is fun , The key is to understand the technology thoroughly .
Welcome to wechat , Like support collection !
author[Lei Xuewei],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
guess what you like
Daily python, Chapter 18, class
"I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
Python implements filtering emoticons in text
When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
Python crawler - get fund change information
Highlight actor using Python VTK
Python crawler actual combat: crawling southern weekend news articles
leetcode 406. Queue Reconstruction by Height（python）
leetcode 1043. Partition Array for Maximum Sum （python）
- Python * * packaging and unpacking details
- Python realizes weather query function
- Python from 0 to 1 (day 12) - Python data application 2 (STR function)
- Python from 0 to 1 (day 13) - Python data application 3
- Numpy common operations of Python data analysis series Chapter 8
- How to implement mockserver [Python version]
- Van * Python! Write an article and publish the script on multiple platforms
- Python data analysis - file reading
- Python data De duplication and missing value processing
- Python office automation - play with browser
- Python series tutorial 127 -- Reference vs copy
- Control flow in Python: break and continue
- Teach you how to extract tables in PDF with Python
- leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal（python）
- leetcode 1338. Reduce Array Size to The Half（python）
- Object oriented and exception handling in Python
- How to configure load balancing for Django service
- How to embed Python in go
- Python Matplotlib drawing graphics
- Python object-oriented programming 05: concluding summary of classes and objects
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values（python）
- leetcode 1433. Check If a String Can Break Another String（python）
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
- Python crawler series - network requests
- Python thread 01 understanding thread
- Analysis of earthquake distribution in the past 10 years with Python~
- You need to master these before learning Python crawlers
- After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
- Python uses redis
- Python crawler - ETF fund acquisition
- Detailed tutorial on Python operation Tencent object storage (COS)
- [Python] comparison of list, tuple, array and bidirectional queue methods
- Go Python 3 usage and pit Prevention Guide