Python process and thread, Python process thread
Process: A basic unit for memory allocation by the operating system. The memory between processes is isolated from each other. If processes need to communicate with each other, an IPC Mechanism is required for the process.
Thread: A process can be divided into multiple threads. A thread is the execution unit of the process and the basic unit for CPU allocation by the operating system. thread
Why use multi-process and multi-thread?
If a task is executed for a long time, it can be divided into multiple threads or processes,
Improve Execution efficiency, program performance, and execution time
Improve user experience and improve user experience
Process
multiprocessingThe module providesProcessClass to represent a process object
import timefrom multiprocessing import Processimport oscount = 0def output(string): global count while count < 10: print(string, end='', flush=True) count += 1def main(): p1 = Process(target=output, args=('Ping', )) p1.start() p2 = Process(target=output, args=('Pong',)) p2.start()Multithreading
Multi-task can be completed by multiple processes, or by multiple threads in a process.
We mentioned earlier that a process is composed of several threads. A process has at least one thread.
Since threads are execution units directly supported by the operating system, high-level languages usually have built-in multi-threaded support, and Python is no exception. In addition, Python threads are real Posix Threads, instead of the simulated thread.
The Python Standard Library provides two modules:_threadAndthreading,_threadIs a low-level module,threadingIs an advanced module._threadEncapsulation. In most cases, we only need to usethreadingThis advanced module.
When a thread is started, a function is passed in and created.ThreadInstance, and then callstart()Start execution
from threading import Threadcount = 0class PrintThread(Thread): def __init__(self, string, count): super().__init__() self._string = string self._count = count def run(self): for _ in range(self._count): print(self._string, end='', flush=True)def main(): PrintThread('Ping', 10).start() PrintThread('Pong', 10).start()
Two ways to create a thread
1. directly create a Thread object and specify the task to be executed after the Thread starts using the target parameter.
2. inherit the Thread custom Thread and specify the task to be executed after the Thread is started by rewriting the run Method