Python 38 process

Concurrent programming

content

  • Operating system history
  • Multi-channel technology
  • Process theory
  • Two ways to start the process
  • Join method of process object
  • Data isolation between processes
  • Other methods of process objects
  • Zombie process and orphan process
  • Daemon
  • Mutex

Essential knowledge review

  • The computer is also called the computer, that is, the brain with electricity. The computer was invented to enable him to work like a human after being powered on, and it is more efficient than human because it can be uninterrupted for 24 hours.

  • The five major components of a computer

    Controller

    Operator

    Memory

    input device

    Output device

    The core of the computer really works is the CPU (controller + arithmetic unit = central processing unit)

  • For a program to be run by a computer, its code must be read from the hard disk to memory, and then the CPU fetches instructions before executing

Operating system history

Just refer to the blog: https://www.cnblogs.com/Dominic-Ji/articles/10929381.html

Multi-channel technology

Single core achieves concurrent effect

Required knowledge

  • Concurrency

    It looks like running concurrently can be called concurrent

  • parallel

    Real simultaneous execution

ps:

  • Parallel must be considered concurrent
  • Single-core computers certainly cannot achieve parallelism, but they can achieve concurrency! ! !

Supplement: We directly assume that a single core is a core, and only one person works, don't consider the number of cores in the CPU

Multi-channel technical illustration

Save the total time spent running multiple programs

Reference group screenshot

Multi-channel technology key knowledge

Taking in space and taking in time

  • Spatial multiplexing

    Multiple programs share a set of computer hardware

  • Multiplexing in time

    Example: Washing clothes for 30s, cooking for 50s, boiling water for 30s

    Single channel needs 110s, multiple channels only need the long switch of task to save time

    Example: Playing a game while eating and saving state

Switch + save state

"""
切换(CPU)分为两种情况
	1.当一个程序遇到IO操作的时候,操作系统会剥夺该程序的CPU执行权限
		作用:提高了CPU的利用率 并且也不影响程序的执行效率
	
	2.当一个程序长时间占用CPU的时候,操作吸引也会剥夺该程序的CPU执行权限
		弊端:降低了程序的执行效率(原本时间+切换时间)
"""

Process theory

Required knowledge

The difference between program and process

"""
程序就是一堆躺在硬盘上的代码,是“死”的
进程则表示程序正在执行的过程,是“活”的
"""

Process scheduling

  • First come first served scheduling algorithm

    """对长作业有利,对短作业无益"""
    
  • Short job priority scheduling algorithm

    """对短作业有利,多长作业无益"""
    
  • Time slice rotation method + multi-level feedback queue

    Reference illustration

Three state diagram of process running

Refer to the illustration to understand

Two pairs of important concepts

  • Synchronous and asynchronous

    """描述的是任务的提交方式"""
    同步:任务提交之后,原地等待任务的返回结果,等待的过程中不做任何事(干等)
      	程序层面上表现出来的感觉就是卡住了
    
    异步:任务提交之后,不原地等待任务的返回结果,直接去做其他事情
      	我提交的任务结果如何获取?
        任务的返回结果会有一个异步回调机制自动处理
    
  • Blocking non-blocking

    """描述的程序的运行状态"""
    阻塞:阻塞态
    非阻塞:就绪态、运行态
    
    理想状态:我们应该让我们的写的代码永远处于就绪态和运行态之间切换
    

Combination of the above concepts: the most efficient combination is asynchronous non-blocking

Two ways to start the process

#  方式一:直接调用函数
from multiprocessing import Process
import time


def task(name):
    print(f'子进程{name}开始')
    time.sleep(3)
    print(f'子进程运行{name}结束')


if __name__ == '__main__':
    #  Process是一个类,调用类生成对象p,需要传参
    print(f'主进程开始')
    p=Process(target=task, args=('1',))
    #  所有容器类型哪怕只有一个参数后面也要加逗号,防止是元组
    p.start()
    print(f'主进程结束')

#  方式2:调用类


class MyProcess(Process):
    def __init__(self,name):
        super().__init__()
        self.name=name

    def run(self):
        print(f'子进程{self.name}开始')
        time.sleep(3)
        print(f'子进程{self.name}运行结束')


if __name__ == '__main__':
    print(f'主进程开始')
    p = MyProcess('1')
    p.start()
    print(f'主进程结束')

to sum up

"""
创建进程就是在内存中申请一块内存空间将需要运行的代码丢进去
一个进程对应在内存中就是一块独立的内存空间
多个进程对应在内存中就是多块独立的内存空间
进程与进程之间数据默认情况下是无法直接交互,如果想交互可以借助于第三方工具、模块
"""

join method

Join is to let the main process wait for the sub-process code to finish running before continuing. Does not affect the execution of other child processes

#  join是让主进程等待子进程的结束
from multiprocessing import Process
import time


def task(name, sleep_time):
    print(f'子进程{name}开始')
    time.sleep(sleep_time)
    print(f'子进程运行{name}结束')


if __name__ == '__main__':
    print(f'主进程开始')
    start_time=time.time()
    tup=('egon', 'tank', 'json',)
    p_list=[]
    for i,name in enumerate(tup):
        p = Process(target=task, args=(name, i,))
        p.start()
        p_list.append(p)
    for p in p_list:
        p.join()

    print(f'主进程结束',time.time()-start_time)

Data between processes is isolated from each other

from multiprocessing import Process

money = 100


def task():
    global money
    money = 666
    print(money)


if __name__ == '__main__':
    p = Process(target=task)
    p.start()
    p.join()
    print(money)

Guess you like

Origin www.cnblogs.com/Franciszw/p/12753698.html
38
Recommended