Python multi-process and multi-thread basics

Regarding the basic knowledge of processes and threads, some articles have been shared before, and some basic knowledge will be summarized below (emphasis: frequently asked interviews):

The running status of the process

1 ) New State: The process is being created and has not yet turned to the ready state.

2 ) Ready state: All operating conditions have been met, waiting for the CPU.

3 ) Run Status (Execution Window): The process is running on the processor.

4 ) Blocking state: The process is waiting for an event and suspended. Such as waiting for available resources or waiting for input and output to complete. Even if the processor is idle, the process cannot run.

5 ) Death state: The process is disappearing from the system.

The three basic states of the process are interchangeable

Ready——>Run: When the process gets the processor, it changes from the ready state to the running state.

Run -> Ready: When a process is deprived of the processor, if the time slice allocated to it by the system is used up, other higher-level processes appear, and the process changes from the running state to the ready state.

Operation -> Blocking: When the running process is blocked due to an event, such as the requested resource is occupied, and the start I/O transmission is not completed, the process changes from the running state to the blocking state.

Blocking——>Ready: When the waiting event occurs, if the requested resource is obtained, the I/O transmission is completed, and the process changes from blocking to ready state

How to use multiple processes in Python

Use the multiprocessing module to create a process in Python

The multiprocessing module provides a Process class to create process objects.

Process([group],[target],[ name ],[args],[ kwargs])
group: Specify the process group, not used in most cases,In general, group can only be assigned to None
target: If the reference of the function is passed, the child process can execute the code here, target=Function name, the function name cannot have parentheses
args: The parameters passed to the function specified by target are passed as tuples. args=(5,), If there is only one parameter, a comma must be added to indicate a tuple
kwargs: Pass named parameters to the function specified by target, usually in the form of a dictionary, kwargs={"Formal parameter 1": "Actual parameter 1", "formal parameter 2": "actual parameter 2"}
name: Set a name for the process, you don’t need to set it

Common methods of instance objects created by Process

Use the Process class to create a multi-process

# Import multi-process modules
import  multiprocessing
import os
def target_func():print("Child process name",multiprocessing.current_process().name)print("Child process PID:",os.getpid())print("The parent process ppid of the child process:",os.getppid())if __name__ =='__main__':for i inrange(3):
  # Create a process instance, specify the target function to be executed
  p = multiprocessing.Process(target=target_func)
  p.start()#Use the start method to start the process
  p.join()#Wait for the child process to end
  print("Main process pid:",os.getpid())
 Output:
Child process name Process-1
Child process PID: 3708
The parent process ppid of the child process:4256
Main process pid: 4256
Child process name Process-2
Child process PID: 8460
The parent process ppid of the child process:4256
Main process pid: 4256
Child process name Process-3
Child process PID: 4468
The parent process ppid of the child process:4256
Main process pid: 4256

How to use multithreading in Python

In python, the threading module is used for multi-threaded operation of the program. The threading module provides a Thread class to create threads.

1. The target is the name of the thread executing function, do not have parentheses after the function name.

2. args: The parameters needed to execute the function. This parameter should be passed in the form of a tuple. If there is only one element, don't forget the comma.

3. kwargs: parameters required to execute the function, this parameter should be passed in a dictionary

The Thread class provides the following methods:run():A method used to represent thread activity.
start():Start thread activity.
join([time]):Wait until the thread terminates, and hang until the started thread terminates; unless timeout (seconds) is given, it will remain blocked.
isAlive():Returns whether the thread is active.
getName():Returns the thread name.
setName():Set the thread name.

Common methods and attributes of threading:
threading.currentThread():Returns the current thread variable.
threading.enumerate():Returns a list of running threads. Running refers to the thread after it starts and before it ends, excluding the thread before it starts and after it ends.
threading.activeCount():Returns the number of currently active threads, 1 main thread+n child threads.

Multi-threaded simple use

import threading #Import multi-threaded module

def eat():print('eating')print('Thread name%s'%threading.current_thread().name)
def dance():print('is dancing')print('Thread name%s'%threading.current_thread().name)
def song():print('singing')print('Thread name%s'%threading.current_thread().name)if __name__ =='__main__':

 thread =[] #Define an empty list to save threads
 t1 = threading.Thread(target=eat,args=('')) #Define the first thread
 t2 = threading.Thread(target=dance,args=('')) #Define the second thread
 t3 = threading.Thread(target=song,args=('')) #Define the third thread
 thread.append(t1) #Add threads to the list in turn
 thread.append(t2)
 thread.append(t3)for i in thread:
  i.start() #Start all threads in sequence
 for i in thread:
  i.join()  #Guard all threads

Output:
eating
Thread name Thread-1
is dancing
Thread name Thread-2
singing
Thread name Thread-3

Recommended Posts

Python multi-process and multi-thread basics
Python basics
Python basics 2
Python basics
Python basics 3
Python basics 4
Python basics 5
Python and Go
Python object-oriented basics
Python introspection and reflection
Python custom function basics
[python] python2 and python3 under ubuntu
Basics of Python syntax
Python deconstruction and packaging
Python3 configuration and entry.md
Python automated operation and maintenance 2
Python introduction and environment installation
Python know crawler and anti crawler
centos7 install python3 and ipython
Centos 6.10 reinstall python and yum
Python open read and write
CentOS7 install python3 and pip3
Python data structure and algorithm
CentOS 6.9 compile and install python
CentOS 6 compile and install python 3
Generators and iterators in Python
Python file read and write operations
Python and js interactive call method
Magic methods and uses of Python
Python judges positive and negative numbers
python ftp upload files and folders
Python crawler | Cognitive crawler request and response
Python implements string and number splicing
Python function definition and parameter explanation
CentOS quickly install Python3 and pip3
Mongodb and python interaction of python crawler
Install Python3 and ansible under CentOS8
Python processing PDF and CDF examples
Played with stocks and learned Python
Configure python3 environment on centos7 and
Python reads and writes json files
Python implements username and password verification
Install Python3 and Py under CentOS7
Linux basics (Ubuntu copy and paste)
Python basic syntax and number types
Python learning os module and usage