current position:Home>Python thread 01 understanding thread
Python thread 01 understanding thread
2022-02-01 02:52:10 【Lei Xuewei】
「 This is my participation 11 The fourth of the yuegengwen challenge 18 God , Check out the activity details :2021 One last more challenge 」
ceremonial Python Column No 41 piece , Classmate, stop , Don't miss this from 0 The beginning of the article !
The previous article has written a lot , They are all relatively basic .
At the beginning of this article, we will enter intermediate programming . Deal with more complex things . For example, the thread in this article , Let's start with the basics !
What is thread ?
We know that all the workers work in the factory at the same time , Copy their work . They are an independent unit !
Threads are similar to this Independent operating unit , Multithreading , That's more than one. Independent operating unit , Do the same thing at the same time .
In this simple way , We'll compare later .
Thread stateful , It's appropriate to compare the state of workers in a day , Go to work in the morning , And then work , Sometimes you need to stop and rest , Finally, I got off work .
Copy and 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
mythread = threading.Thread()
print("mythread:", mythread)
print("is_alive:", mythread.is_alive())
mythread.start()
print("mythread:", mythread)
print("is_alive:", mythread.is_alive())
Copy code
Here are the results :
Readers are advised to run .
Let's explain the thread code
We used threading This library , Then create Thread Object instance of class , Assign a value to mythread Variable .
Then print a function of the object and thread object is_alive() Is active .
Both times False( We'll talk about that later )
But the second time we saw the thread object print out and become ‘stopped'.
That means we're done start function ( This function is the thread startup function ) after , The thread goes into stopped Status quo .
The one above is the thread , But it seems that nothing has been done , Let's let it do something .
Thread triggers business function , Thread calls business function
For example, the business this time is : Focus and like .
def dianzan_guanzhu():
now = datetime.datetime.now() # Initialize time variable
name = "python Adorable new "
print("%s name:%s" % (now, name)) # First print time and fan name
time.sleep(1)
result = " very good !" + name + " Pay attention to Lei Xuewei , Bai whoring has a lot of knowledge and development experience !"
print("%s result:%s" % (now, result)) # Second printing time and fan activities
return result
Copy code
Let's look at the code below :
#!/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
""" The school committee defined a focus function """
def dianzan_guanzhu():
now = datetime.datetime.now()
name = "python Adorable new "
print("%s name:%s" % (now, name))
time.sleep(1)
result = " very good !" + name + " Pay attention to Lei Xuewei , Bai whoring has a lot of knowledge and development experience !"
print("%s result:%s" % (now, result))
return result
mythread = threading.Thread(target=dianzan_guanzhu)
print("mythread:", mythread)
print("is_alive:", mythread.is_alive())
mythread.start()
print("mythread:", mythread)
print("is_alive:", mythread.is_alive())
dianzan_guanzhu()
print("is_alive:", mythread.is_alive())
Copy code
Direct copy run , Here we are dianzan_guanzhu Function called two
The first is mythread.start function .
The second time we call directly from the thread dianzan_guanzhu function .
Here are the results :
It seems nothing .
Look again , Be careful Pay attention to the time of each print , The input time seems to be out of order ? you 're right , Not dazzled , Is the result of correct operation .
Because of entering dianzan_guanzhu After the function , Initialize the now Variable , This time is fixed .
But it also calls... Outside the thread dianzan_guanzhu function , So this is : Two threads are doing the same thing at the same time .
Which one more thread is ?
Add here , We write python Script , When running the code , Itself is in a The main thread Medium .
It's just that I haven't released the concept of thread before , No multithreading program , Didn't feel it .
from now on , You have to be clear that : Every program runs with a The main thread .
Back to the result , The two threads call the pass function in turn :
First , Print the first line of output successively .
Sleep separately for a second (sleep(1)).
Last , Print the second line of output successively .
summary
Let's first understand the basic knowledge of threads . The next section will share more about threads .
by the way , 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 !
copyright notice
author[Lei Xuewei],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010252090325.html
The sidebar is recommended
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors(python)
- leetcode 1910. Remove All Occurrences of a Substring(python)
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
guess what you like
-
Python connects redis, singleton and thread pool, and resolves problems encountered
-
Python from 0 to 1 (day 11) - Python data application 1
-
Python bisect module
-
Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
-
Use the properties of Python VTK implicit functions to select and cut data
-
Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
-
leetcode 986. Interval List Intersections(python)
-
leetcode 1860. Incremental Memory Leak(python)
-
How to teach yourself Python? How long will it take?
-
Python Matplotlib drawing pie chart
Random 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
- 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!"
- Django view
- 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