Let's first look at the computer architecture Threads The concept of .
In calculation , process Is an instance of a computer program being executed . Any process has 3 Basic components :
Threads Is an entity in a process that can be scheduled for execution . Besides , It is available in the operating system ( operating system ) The smallest processing unit executed in .
Simply speaking , Threads Is a sequence of such instructions in a program that can be executed independently of other code . For the sake of simplicity , You can assume that threads are just a subset of processes !
The thread is in Thread control block (TCB) Contains all this information :
Please refer to the following figure to understand the relationship between a process and its threads :
There can be multiple threads in a process , among :
Refer to the figure below to see how multiple threads exist in memory :
stay Python in , Threads The module provides a very simple and intuitive API, Used to generate multiple threads in a program .
Let's consider a simple example of using a threading module :
import threading
def print_cube(num):
""" A function for printing a cube of a given number """
print("Cube: {}".format(num * num * num))
def print_square(num):
""" Function prints the square of a given number """
print("Square: {}".format(num * num))
if __name__ == "__main__":
# Create thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# Start thread 1
t1.start()
# Start thread 2
t2.start()
# Wait for thread 1 Fully implement
t1.join()
# Wait for thread 2 Fully implement
t2.join()
# Both threads are fully executed
print("Done!")
Running results :
Let's try to understand the above code :
To import the thread module , We need to :
import threading
To create a new thread , We create a Thread Class object . It requires the following parameters :
In the example above , We created 2 Threads with different objective functions :
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
To start a thread , We use Thread Class start Method .
t1.start()
t2.start()
Once the thread starts , Current procedure ( You can think of it as a main thread ) Will continue to carry out . To stop the execution of the current program , Until the thread completes , We use Connect Method .
t1.join()
t2.join()
therefore , The current program will first wait t1 Completion , And then wait t2 complete . After completion , The remaining statements of the current program will be executed .
Consider the image below , To better understand how the above procedure works :
Consider the following python Program , Where we print the thread name and the corresponding process for each task :
import threading
import os
def task1():
print(" Mission 1 Assign to thread : {}".format(threading.current_thread().name))
print(" Run the task 1 The process of ID: {}".format(os.getpid()))
def task2():
print(" Mission 2 Assign to thread : {}".format(threading.current_thread().name))
print(" Run the task 2 The process of ID: {}".format(os.getpid()))
if __name__ == "__main__":
# Print the of the current process ID
print(" The process that runs the main program ID: {}".format(os.getpid()))
# Print the main thread name
print(" Main thread name : {}".format(threading.current_thread().name))
# Create thread
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')
# Start thread
t1.start()
t2.start()
# Wait for all threads to finish
t1.join()
t2.join()
Running results :
Let's try to understand the above code :
We use os.getpid() Function to get the of the current process ID.
print(" The process that runs the main program ID: {}".format(os.getpid()))
It is clear from the output that , All threaded processes ID All remain the same .
We use threading.main_thread() Function to get the main thread object . Under normal circumstances , The main thread is to start Python Interpreter thread . Of Thread objects name Property is used to get the name of the thread .
print(" Main thread name : {}".format(threading.main_thread().name))
We use threading.current_thread() Function to get the current thread object .
print(" Mission 1 Allocated threads : {}".format(threading.current_thread().name))
The following figure illustrates the above concepts :