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 :

 Screenshot  2021-11-21  In the morning 12.09.32.png

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 :

 Screenshot  2021-11-21  In the morning 11.32.00.png

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

Random recommended