Learn some Python multithreaded programming in your spare time

β˜€οΈ preface β˜€οΈ

School has begun, school has begun, school has begun, let's study together~~

Learn some Python in your spare time. You will also have some skills in the future. Pay attention to me and we will make a little progress every day.

πŸ™€ Introduction to the author πŸ™€

Hello everyone, I'm bu Xiaochan, an IT Xiaobai who tries to make the ruthless code lively and interesting. I'm glad to know you, pay attention to me and insist on learning something every day. We'll be big guys in the future!

πŸ“’ Blog home page: ❀ Bu Xiaochan ❀
πŸ“’ Author column:
❀Python❀
❀Java❀
[ ❀ Force deduction question ❀

πŸ’Œ 1, Multithreading πŸ’Œ

First understand the differences between processes and threads

  • Process:

Take the computer for example, the process is QQ, wechat and other different programs

Take the PY file as an example, that is, how many py files do you have

  • Thread:

Take the computer for example, QQ. You can chat with many people in wechat

Take the py file as an example, that is, many of your functions in the py file

one ️⃣ Multithreaded programming 🌈

What is multithreading? Generally speaking, let your code do several things at the same time.

A code file or a project is a process. If we want to improve efficiency, we can open several more files for multiple processes, or create multiple threads in the process (write more methods). However, multiple processes consume resources, so we generally recommend multithreading. In the code, let the code do what several files do.

Multithreaded programming can make our code more efficient

two ️⃣ Working process of thread 🏰

To use multithreading, you need to create one or more threads first

Then let the thread call CPU resources and start running

Then wait for all threads to run

Then delete the resource and end the thread

three ️⃣ Introduction to threading module πŸ’’

Multithreading is out of order

Neither task will be completed in sequence

Python's built-in threading module allows us to simply use multithreading

theading module also has many methods:

  • threading.currentThread(): returns the current thread variable.
  • threading.enumerate(): returns a list of running threads. Running refers to threads after starting and before ending, excluding threads before starting and after termination.
  • threading.activeCount(): returns the number of running threads, which is the same as len(threading.enumerate()).

In addition to using methods, the thread module also provides thread class to process threads. Thread class provides the following methods:

  • run(): the method used to represent thread activity.

  • start():

    Start thread activity.

  • join([time]): wait until the thread aborts. This blocks the calling thread until the thread's join() method is called to abort - exit normally or throw an unhandled exception - or an optional timeout occurs.

  • isAlive(): Returns whether the thread is active.

  • getName(): returns the thread name.

  • setName(): sets the thread name.

In our small case, we will not use other methods. We will only use a start method to start our thread and a join method to block the process.

Why block threads:

Because our threads are out of order

Not necessarily which one is completed first

The function of join is to let the thread wait for the main thread to execute after execution, and then destroy the thread

four ️⃣ Multithreaded programming practice πŸ’°

Code requirements:

  • Please define a function to traverse three arrays

  • And three times

  • Reduce the program running time as little as possible

Pseudo code flow:

# Code start
def A traversal function:
    Traverse three lists
li = []
li2 = []
li3 = []
Start multithreading according to the dead formula
 Wait for the program to run

In fact, it's so simple. You can omit and memorize everything you find difficult. You only need to know his role, not why he can do it

code:

import threading  # Import module

# Define function
def speak(a, b, c):
    for i, j, l in zip(a, b, c):
        print("I am",i,"\n", "My blog home page is:", j, "\n", "We formed it together Python The group number is:", l)

# Define function parameters
li = ["Lei Xuewei", "Solitary cold", "Bu Xiaochan", "Dragon juvenile", "yunlord"]
li2 = ['https://blog.csdn.net/geeklevin', 'https://blog.csdn.net/qq_44907926', 'https://blog.csdn.net/m0_52883898', 'https://blog.csdn.net/hhladminhhl', 'https://blog.csdn.net/kobepaul123']
li3 = ["790839397", "790839397", "790839397", "790839397", "790839397"]

# Turn on Multithreading
s1 = threading.Thread(target=speak, args=(li,li2,li3))
s1.start()
s2 = threading.Thread(target=speak, args=(li,li2,li3))
s2.start()
s3 = threading.Thread(target=speak, args=(li,li2,li3))
s3.start()

Operation results:

"""
I'm Lei Xuewei. I'm Lei Xuewei  

 My blog home page is: I am my blog home page is: https://Blog.csdn.net/geeklevin thunder Science Committee https://blog.csdn.net/geeklevin 
 
 
 We formed it together Python The group number is: my blog home page is: we set up together Python The group number is 7908397 https://blog.csdn.net/geeklevin  
790839397 I am

 I'm a lonely cold. We set up together Python The group number is: lonely cold 
 790839397 

My blog home page is: I am my blog home page is: https://blog.csdn.net/qq_44907926 lonely cold https://blog.csdn.net/qq_ forty-four million nine hundred and seven thousand nine hundred and twenty-six 
 
 
 We formed it together Python The group number is: my blog home page is: we set up together Python The group number is 7908397 https://blog.csdn.net/qq_44907926
790839397 I am

 We formed it together Python The group number is: I'm 790839397 Bu Xiaochan
 Bu Xiaochan I am

 Bu Xiaochan my blog home page is: my blog home page is:
 https://blog.csdn.net/m0_52883898 https://blog.csdn.net/m0_52883898
 My blog home page is:
 We formed it together Python The group number is: https://blog.csdn.net/m0_52883898 the Python group number we set up together is 7908397

790839397 I am
 We formed it together Python The group number is: I am Dragon Juvenile 7908397 Dragon juvenile

 I am
 My blog home page is: Dragon My blog home page is: https://blog.csdn.net/hhladminhhl
 https://blog.csdn.net/hhladminhhl
 My blog home page is:
 We formed it together Python The group number is: https://blog.csdn.net/hhladminhhl the Python group number we set up together is 790839397 7908397


I am. I was formed together Python The group number is: yunlord yunlord 790839397


 I am my blog home page is: my blog home page is: yunlord https://blog.csdn.net/kobepaul123 https://blog.csdn.net/kobepaul123


 My blog home page is: we set up together Python The group number is: we set up together Python The group number is 7908397 https://blog.csdn.net/kobepaul123
790839397

 We formed it together Python The group number is 7908397
"""

Look, I'm right. Multithreading has disorder, but it does improve your running speed.

πŸ’° Custom thread class ⭐

If we want to customize the thread class, we need to inherit the Thead class of theading module and rewrite the run party. Each custom thread class needs to rewrite the run method, and the start method calls the run method

import threading

# Define execution parameters
li = ["Lei Xuewei", "Solitary cold", "Bu Xiaochan", "Dragon juvenile", "yunlord"]
li2 = ['https://blog.csdn.net/geeklevin', 'https://blog.csdn.net/qq_44907926', 'https://blog.csdn.net/m0_52883898', 'https://blog.csdn.net/hhladminhhl', 'https://blog.csdn.net/kobepaul123']
li3 = ["790839397", "790839397", "790839397", "790839397", "790839397"]

# Define execution function
def speak(a, b, c):
    for i, j, l in zip(a, b, c):
        print("I am",i,"\n", "My blog home page is:", j, "\n", "We formed it together Python The group number is:", l)

# Custom thread class
class MyThread(threading.Thread):
    def __init__(self,n):
         threading.Thread.__init__(self)   
         self.n = n
    def run(self):
        print("Thread:",self.n, "open")   # Prompt that the thread is turned on
        speak(li, li2, li3)
        print("Thread:",self.n, "close")   # Closing prompt for thread completion
        return super().run()   #The refactoring run function must write

# Instantiate thread class
s1 = MyThread("thread1")
s2 = MyThread("thread1")

# Open thread class
s1.start()
s2.start()

# Blocking thread class
s1.join()
s2.join()

print("After all threads are executed, the main thread ends")

Code running effect:

Thread: thread1 Threads: on thread1
 I'm opening
 Lei Xuewei, I am
 The homepage of Lei Xuewei's blog is:
  https://blog.csdn.net/geeklevin my blog home page is:
https://blog.csdn.net/geeklevin our Python group number is:
  790839397 We formed it together Python The group number is:
 My name is 7908397
 I am the lonely cold

  My blog home page is: my blog home page is:  https://blog.csdn.net/qq_44907926https://blog.csdn.net/qq_44907926

  We formed it together Python The group number is: we set up together Python The group number is 7908397790839397

I'm bu Xiaochan I'm bu Xiaochan

  My blog home page is: my blog home page is:  https://blog.csdn.net/m0_52883898https://blog.csdn.net/m0_52883898

  We formed it together Python The group number is: we set up together Python The group number is 7908397790839397

I am I am  Dragon juvenile Dragon juvenile

  My blog home page is: my blog home page is:  https://blog.csdn.net/hhladminhhlhttps://blog.csdn.net/hhladminhhl

  We formed it together Python The group number is 7908397. We formed it together Python The group number is:
 My name is 7908397
yunlord I am
yunlord  My blog home page is:
  https://Blog.csdn.net/kobepaul123my blog home page is:
https://blog.csdn.net/kobepaul123
 We formed it together Python The group number is: we set up together Python The group number is 7908397
790839397 Thread:
 Thread: thread1  thread1 close
 close
 After all threads are executed, the main thread ends

🌹 epilogue 🌹

Interest is the best teacher, and persistence is the invariable truth.
Learn not to be impatient, step by step, and move forward steadily.
Make a little progress every day. Over time, you will find that you have become very powerful.

I am Bu Xiaochan, a self-taught sprouting new, follow me to make progress a little every day!

It's enough to say so much for the time being, so let's leave

Tags: Python Multithreading

Posted on Fri, 10 Sep 2021 21:39:18 -0400 by metomeya