SoFunction
Updated on 2025-03-02

Detailed explanation of the status, creation and usage of python process

This article describes the status, creation and usage of python processes. Share it for your reference, as follows:

Process and status

1. Process

Program: For example, this is a program, which is a static one.

Process: After a program is run, the code + the resource used is called a process, which is the basic unit of the operating system allocates resources.

Not only can multitask be completed through threads, but also processes can

2. Process status

During work, the number of tasks is often greater than the number of cores of CPU, that is, some tasks must be executed, while other tasks are waiting for CPU to execute, which leads to different states.

  • Ready: The running conditions have slowed down and are waiting for CPU execution
  • Executing state: CPU is executing its function
  • Waiting state: Waiting for certain conditions to be met, for example, a program sleeps, and it is in a waiting state at this time

Process creation - multiprocessing

The multiprocessing module is a cross-platform version of multiprocess module, providing a Process class to represent a process object. This object can be understood as an independent process and can perform other things

1. 2 while loops are executed together

# -*- coding:utf-8 -*-
from multiprocessing import Process
import time
def run_proc():
  """Code to be executed by the child process"""
  while True:
    print("----2----")
    (1)
if __name__=='__main__':
  p = Process(target=run_proc)
  ()
  while True:
    print("----1----")
    (1)

illustrate

  • When creating a child process, you only need to pass in one parameter to execute the function and function, create a Process instance, and start with the start() method.

2. Process pid

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
import time
def run_proc():
  """Code to be executed by the child process"""
  print('The child process is running,pid=%d...' % ()) # Get the process number of the current process  print('The child process is about to end...')
if __name__ == '__main__':
  print('Parent process pid: %d' % ()) # Get the process number of the current process  p = Process(target=run_proc)
  ()

3. The Process syntax structure is as follows:

Process([group [, target [, name [, args [, kwargs]]]]])

  • target: If a function reference is passed, you can execute the code here by tasking this child process.
  • args: The parameters passed to the function specified by the target, passed in tuple
  • kwargs: Pass named parameters to the function specified by target.
  • name: Set a name for the process, but it can not be set.
  • group: Specify the process group, in most cases it cannot be used

Common methods for instance objects created by Process:

  • start(): Start the child process instance (create the child process)
  • is_alive(): determines whether the process child process is still alive
  • join([timeout]): Whether to wait for the child process to end, or how many seconds to wait
  • terminate(): terminate the child process immediately regardless of whether the task is completed or not.

Common properties of instance objects created by Process:

  • name: the alias of the current process, default to Process-N, N is an integer incremented from 1
  • pid: the pid of the current process (process number)

4. Pass parameters to the function specified by the child process

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
from time import sleep
def run_proc(name, age, **kwargs):
  for i in range(10):
    print('The child process is running,name= %s,age=%d ,pid=%d...' % (name, age, ()))
    print(kwargs)
    sleep(0.2)
if __name__=='__main__':
  p = Process(target=run_proc, args=('test',18), kwargs={"m":20})
  ()
  sleep(1) # After 1 second, end the child process immediately  ()
  ()

Running results:

The child process is running, name=test,age=18,pid=45097...
{'m': 20}
The child process is running, name=test,age=18,pid=45097...
{'m': 20}
The child process is running, name=test,age=18,pid=45097...
{'m': 20}
The child process is running, name=test,age=18,pid=45097...
{'m': 20}
The child process is running, name=test,age=18,pid=45097...
{'m': 20}

5. Different global variables are shared between processes

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
import time
nums = [11, 22]
def work1():
  """Code to be executed by the child process"""
  print("in process1 pid=%d ,nums=%s" % ((), nums))
  for i in range(3):
    (i)
    (1)
    print("in process1 pid=%d ,nums=%s" % ((), nums))
def work2():
  """Code to be executed by the child process"""
  print("in process2 pid=%d ,nums=%s" % ((), nums))
if __name__ == '__main__':
  p1 = Process(target=work1)
  ()
  ()
  p2 = Process(target=work2)
  ()

Running results:

in process1 pid=11349 ,nums=[11, 22]
in process1 pid=11349 ,nums=[11, 22, 0]
in process1 pid=11349 ,nums=[11, 22, 0, 1]
in process1 pid=11349 ,nums=[11, 22, 0, 1, 2]
in process2 pid=11350 ,nums=[11, 22]

For more information about Python-related content, please check out the topic of this site:Summary of Python process and thread operation skills》、《Python data structure and algorithm tutorial》、《Summary of Python function usage tips》、《Summary of Python string operation skills》、《Python introduction and advanced classic tutorials》、《Python+MySQL database programming tutorial"and"Summary of common Python database operation skills

I hope this article will be helpful to everyone's Python programming.