Multiple processes, as the name implies, run multiple processes at the start of a program, and each process initiates a thread for program processing. A single piece of memory resource is partitioned without starting a process. It's like a factory building. In order to improve efficiency, add one more production line and then build a separate plant. Each plant is independent of each other. So the start of multi-process is very resource-intensive, after all, the factory covers more factory there is no place for other facilities to use.
A multi-Process code implementation method is similar to a multithreaded function.
#!/usr/bin/env python#-*-coding:utf-8-*-from multiprocessing import process# The referenced module becomes a multi-process module Def foo (i): print ' Say hi ', if or I in range (10): "" "Start 10 processes at the same time, instantiate process () to P call P.start () method to start each process" "" P = Process (target=foo,args= (i,)) P.start ()
As mentioned above, the data between multiple processes is independent, so let's write a code to test
#!/usr/bin/env python#coding:utf-8 from multiprocessing import Process li = [] def foo (i): #向列表中加入当前的进程序列号 li.append (i) print ' Say hi ', Li for I in range: p = Process (target=foo,args= (i,)) P.start () print ' ending ', Li
The above code runs as a result
[email protected] ~]$ python test.py say hi [0]say hi [1]say hi [2]say hi [3]say hi] [4]say hi [5]say hi [6]say hi] [7]say hi [8]ending []say Hi [9]
Take a look at ending [] this column. Through the code we know that each derived child process invokes the Foo () function and adds its own process run serial number to the Li table. But when we finally look at what's stored in the li[] table, we don't see what we want [0,1,2...9] to see. This is actually the process of memory independent of each other caused. We created process 0, then the process copied an empty list li[] and appended 0 to the table. So for the process to say Li list content is li[0]. However, Process 1 has also copied an empty list after booting and process 01 like li[], and for process 1, the content of its own list Li is li[1]. And so on, 10 sub-processes were started and 10 li[] empty lists were copied. The list in each process is independent of each other, and at the end of the program we print the list of the li[] of the most main process, which has not been manipulated so it is empty. Through this we can also know that when the multi-process, each process will have to replicate the resources. So the process starts much more and consumes resources abnormally.
This article from "Thunderbolt Tofu" blog, declined reprint!
Python concurrent Multi-process