[Python] Multi-threaded programming ② (process and thread | process memory space | parallel execution concept | thread creation and execution | threading.Thread() function analysis)





1. Process and thread




1. The memory space of the process


In the operating system, the memory space between processes is isolated, and different processes have their own memory space,

These memory spaces are counted from 0, but these memory spaces only account for a small part of the total memory;


There can be several threads in a process, and these threads share the memory space of the process;


A process can only access the memory space allocated by the operating system, and cannot access the memory space of other processes;

  • In the figure below, process A can only access its own memory, but cannot access the memory of process B;

insert image description here


2. Shared memory between threads


Several threads in a process can share the memory space of the process;

A thread can only access the memory space of its own process, and cannot access the memory space of other processes;


3. The concept of parallel execution


Processes can be executed in parallel, and multiple processes in the operating system can do different jobs at the same time;

Threads can be executed in parallel, and multiple threads in a process can do different jobs at the same time;





2. Python multi-threaded programming




1. Thread creation and execution


All programming languages ​​allow multi-threaded programming, Python also supports multi-threaded programming;

Python multi-threaded programming functionality is provided by the threading module;


In Python, for multi-threaded programming,

First, you need to import the threading module;

import threading

Then, execute the threading.Thread() method to create a thread instance object;

thread_obj = threading.Thread()

Finally, call the thread object #start() function to start the thread;

thread_obj.start()

2. Analysis of threading.Thread() function


The threading.Thread() function is used to create a new thread object, and can configure the behavior of the thread by specifying the thread function and parameters;


The threading.Thread function prototype is as follows:

threading.Thread(target=None, args=(), kwargs={
    
    })
  • target parameter: the function to be executed in the thread, specifies the operation to be performed by the thread after startup, the default value is None;
  • args parameter: the type is a tuple, including the parameters passed to the thread function, the default is () empty tuple, and the elements cannot be changed;
  • kwargs parameter: the type is a dictionary, containing the keyword parameters passed to the thread function, the default is {} empty dictionary;

After the thread object is created, the thread instance object will be returned, and the start() method of the thread instance object can be called to start the thread;

After the thread is started, it will be executed independently in the background, and can run in parallel with other threads in the process;


3. Code example - thread creation and operation


In the code below,

First, a function named hello is defined as a thread function,

Then, call the threading.Thread() function to create a new thread instance object,

The target=hello keyword specifies that the thread executes the hello function,

Specify the parameters of the hello function through the kwargs keyword, the name parameter value is "Tom" string, the age parameter value is 18 digital type,

kwargs={
    
    "name": "Tom", "age": 18}   # 指定关键字参数

Then, call the start() method of the function instance object to start the thread;

Finally, the main thread continues with other operations;


Code example:

"""
多线程 代码示例
"""

import threading


# 线程中要执行的函数
def hello(name: str, age: int):
    print(f"Hello {
      
      name}, {
      
      age} years old") # 输出: Hello Tom, 18 years old


# 创建线程对象
thread_obj = threading.Thread(
    target=hello,                       # 指定线程中要执行的函数
    kwargs={
    
    "name": "Tom", "age": 18}   # 指定关键字参数
)

# 启动线程
thread_obj.start()

# 主线程继续执行其他操作
print("继续执行后续操作")

Results of the :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
Hello Tom, 18 years old
继续执行后续操作

Process finished with exit code 0

insert image description here


4. Code example - threads running in parallel


In the code below,

First, two functions are defined, both of which take a long time to execute;

# 线程中要执行的函数 1
def sing():
    for i in range(3):
        print(f"{
      
      i} 唱歌")
        time.sleep(1)


# 线程中要执行的函数 2
def dance():
    for i in range(3):
        print(f"{
      
      i} 跳舞")
        time.sleep(1)

Then, create two threads to execute the above two functions respectively;

    # 创建唱歌线程
    thread_sing = threading.Thread(target=sing)
    # 创建跳舞线程
    thread_dance = threading.Thread(target=dance)

Finally, start two threads, and the command line output of the two threads will be printed alternately;

    # 执行线程
    thread_sing.start()
    thread_dance.start()

Code example:

"""
多线程代码示例
"""

import time
import threading


# 线程中要执行的函数 1
def sing():
    for i in range(3):
        print(f"{
      
      i} 唱歌")
        time.sleep(1)


# 线程中要执行的函数 2
def dance():
    for i in range(3):
        print(f"{
      
      i} 跳舞")
        time.sleep(1)


if __name__ == '__main__':
    # 创建唱歌线程
    thread_sing = threading.Thread(target=sing)
    # 创建跳舞线程
    thread_dance = threading.Thread(target=dance)

    # 执行线程
    thread_sing.start()
    thread_dance.start()

Results of the :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
0 唱歌
0 跳舞
1 跳舞1 唱歌

2 唱歌2 跳舞


Process finished with exit code 0

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/131952845