I. Process theory
1. A process is the smallest unit of resource allocation. 2. The process scheduling is that multiple processes are executed by the CPU under the control of the operating system to enjoy the resources of the computer. First come first service short job priority time slice rotation Multi-level feedback queue 3. Process scheduling process is not able to be arbitrarily affected by the program 4. Three states of a process: ready to run blocking ready state: When a process is assigned to all the necessary resources except the CPU, the process state is called the ready state as long as the processor is available for immediate execution. Run-to-state : When the process gets a processor, its program is executing on the processing machine, at which time the process state is called the running state. Blocking state: Executing program, due to wait for something to happen and can not be executed, then abandon the processor and in a blocking state, causing the process to block the event there are many, waiting for the completion of the IO, waiting for the letter, the request buffer is not satisfied. Eg: after the program starts running, Instead of starting the code immediately, it goes into a ready state, waiting for the operating system schedule to start running import time print ("program starts running") program running state name=input (">> > ") wait for the user input program to enter the blocking state After the user input process is not executed immediately, but into a ready state, waiting for the operating system to continue running the print (name) running state Time.sleep (1) blocking state ready state Print ("program End Run") Run state end 5. Process three-state transition flowchart: A. Create--(submit)-- Ready--(process scheduling)----(free)---(release)--Exit B. Create-(commit)-ready-(Process Scheduler)-run-(time slice end)-ready C. Create--(submit)-- > Ready--(Process Scheduler)----(Event request IO)---(event occurred)--ready 6. PID and PPID pid: ProcessID Process ID PPID: parent ProcessID parental process ID ( Parent process reclaims some of the resources of the child process)
Two. Creation and end of process
1. Process Creation Introduction: But all hardware, need to have the operating system to manage, as long as there are operating systems have the concept of process, you need to have the method of creating the process. For a common system (running many applications), you need to have the ability to create or revoke processes while the system is running. There are four main forms of creating new processes. (1). System initialization (view process Linux with the PS command, Windows with Task Manager, the foreground process is responsible for interacting with the user, the process running in the background is not user-independent, running in the background and only when needed to wake up the process, called daemons, such as "e-mail", " Web page "," News "," print ") (2). A process opens a child process (OS) (3) While it is running . The user's interactive request creates a new process (" Double-click QQ ") (4). Initialization of a batch job ( Used only in mainframe batch systems). Creating sub-processes the similarities and differences between UNIX and Windows: The same: After a process has been created, the parent and child processes have their own different address spaces (multi-channel technology requires a physical level to implement the isolation of memory between processes), and any process Changes in its address space will not affect another process. differences: In Unix, the initial address space for a child process is a copy of the parent process, which indicates that the child process and the parent process can have a read-only shared memory area. However , for Windows systems, the address space of the parent process and the child process is different from the beginning.
2. The end of the process
(1) Normal exit (voluntary, the user clicks the Cross of the interactive page, or the program completes the call to initiate system calls to exit normally, in Linux with exit, in Windows with ExitProcess) (2) Error exits (voluntary, Python a.py a.py not present) (3) Critical Error (involuntary, execution of illegal instructions, such as referencing non-existent memory, can catch exception, try...except ...) (4) Killed by other processes (involuntary, like right-click to end the process
three. Process actions in a Python program
Multiprocess is not a module but a package of operations, management processes in Python. The reason is called Multi is taken from the multiple multi-functional meaning, in this package a few
contains all the sub-modules related to the process. Due to the large number of sub-modules provided, in order to facilitate the classification of memory,
I will be roughly divided into four parts: the creation process part, the Process Synchronization section, the process pool part, the process data sharing.
Multiprocess.process1.process Module Description: The process module is a module that creates processes. With this module, you can complete the process creation. Process ([group [, Target [, name [, args [, Kwargs]]]), an object instantiated by the class that represents a task in a child process (not yet started) emphasizes: (1). You need to specify the parameter (2) by using a keyword. args Specifies the positional parameter passed to the target function, which is a tuple form and must have a comma argument: (1) The group parameter is unused and the value is always none (2) target represents the calling object, that is, the task that the child process is performing (3) args represents the location of the calling object The parameter tuple, args= ("Egon",) (4) Kwargs represents the dictionary of the calling object, kwargs={' name ': ' Egon ', ' Age ': (5) name for the child process description: (1) P.start ( ): Starts the process and calls the P.run () (2) P.run () in the subprocess: The method that runs at the start of the process, which calls the function specified by target, must implement the method in the class of our custom Class (3) p.terminate (): Forces the terminating process p, No cleanup is done, and if p creates a child process, the subprocess becomes a zombie process, and using this method requires special care. If P also holds a lock then it will not be released, causing a deadlock (4) p.is_alive (): If P is still running, return True (5) P.join ([timeout]): The main thread waits for p to terminate (emphasis: is the main thread is in the state, and P is in the running state). Timeout is an optional time-out, and it is important to note that P.join can only join the start-open process, not the process module in Windows that joins the run-open processes: There is no fork in the Windows operating system (The mechanism of creating a process in the Linux operating system), when creating the sub-process will automatically import the launch of its file, and in the import when the entire file was executed. Therefore, if the process () is written directly in the file, it will be infinitely recursive to create the child process error. You must use the IF __name__ = = ' __m to create the part of the child process.Ain__ ' Judgment protection, import, it will not run recursively.
Four. Create a process
(i). Create a process and pass parameters to the child process
ImportOSImport Time fromMultiprocessingImportProcessdefFunc (num):#formal parameter num Print("In func", Num,os.getpid (), Os.getppid ())#4 in func 1 4376 3180 #6 in func 2 20072 3180 Print(__name__)#5 __mp_main__ #7 __mp_main__if __name__=="__main__": Print("In main", Os.getpid (), Os.getppid ())#1 in main 20208 20572P=process (target=func,args= (1,))#keyword pass -throughP.start () P1=process (target=func,args= (2,))#with args, it must be in the form of a tuple (,)P1.start ()Print(__name__)#2 __main__ Print("end of main process")#3 End of main process
Principle:
if __name__ = = ' __main__ ': using Python to invoke the operating system commands to start the process also using Python different operating systems are different for windows that need to add if __name__ = = ' __main__ ': not necessary for Linux iOS add if __name__ = = ' __main__ ':
(b). Other methods and properties
1. Turn on multiple sub-processes
ImportOS fromMultiprocessingImportProcess#Process is a classdefFunc (num):#formal parameter num Print("In func", Num,os.getpid (), Os.getppid ())Print(__name__)#__mp_main__if __name__=="__main__": Print("In main", Os.getpid (), Os.getppid ()) forIinchRange (10): P=process (target=func,args= (i,))#keyword parameters must be in the form of a tuple, separated by commas.P.start ()#submit a request to the operating system to open a child process Print("end of main process")
2.join method
ImportOSImport Time fromMultiprocessingImportProcessdeffunc (num): Time.sleep (1) Print("In func", Num,os.getpid (), Os.getppid ())if __name__=="__main__": Print("In main", Os.getpid (), Os.getppid ()) P=process (target=func,args= (1,)) P.start ()#instead of running a program, you invoke the operating system command to create a child processP.join ()#block until p this child process finishes execution before proceeding with the subsequent code Print('end of code for main process')
3. A batch of tasks with join
ImportOSImport Time fromMultiprocessingImportProcessdeffunc (num):Print("In func", Num,os.getpid (), Os.getppid ())if __name__=="__main__": Print("In main", Os.getpid (), Os.getppid ()) p_l= [] forIinchRange (10): P=process (target=func,args=(i,)) P.start () P_l.append (p)Print(p_l) forPinchP_l:p.join ()Print("main Process Code end")
4.is_alive Terminate
ImportOSImport Time fromMultiprocessingImportProcessdeffunc (num):Print("In func", Num,os.getpid (), Os.getppid ())if __name__=="__main__": Print("In main", Os.getpid (), Os.getppid ()) P=process (target=func,args= (1,)) P.start ()Print(P.is_alive ())#True to detect whether the process is performing a taskP.join ()#blocks wait for the child process to finish before executing the subsequent code Print(P.is_alive ())#False The child process task has endedP.terminate ()#force End Child process non-blocking Print(P.is_alive ())
5. Open child processes in an object-oriented manner
ImportOS fromMultiprocessingImportProcessclassmyprocess (Process):def __init__(Self,num): Super ().__init__() Self.num=NumdefRun (self):Print("In run", Self.num,os.getpid (), Os.getppid ())if __name__=="__main__": Print("In main", Os.getpid (), Os.getppid ()) P=myprocess (1) P.start ()
Python full stack development * Process theory process creation * 180724