Python has thread multiline libraries, but multithreading is not really multi-threading and does not take full advantage of multicore CPU resources.
In most cases, Python can use the multiprocessing multi-process library to easily perform transitions from single-process to concurrent execution.
The multiprocessing library supports sub-processes, communicates and shares data, performs different forms of synchronization, and provides class objects such as process, Queue, Pipe, lock, and so on.
I. Process class objects, creating processes
In multiprocessing, each process is represented by a class process.
Process ([group [, Target [, name [, args [, Kwargs]]]]) parameter: Group group, actually do not use target to represent the calling object, you can pass in the name of the method name is an alias, The equivalent of giving the process a name, args represents the location of the called object tuple, such as Target is function A, he has two parameters m,n, then args passed in (m, N) can kwargs represent the dictionary of the Calling object
Example 1:
Import multiprocessing def process (num): print ' process: ', num if __name__ = = ' __main__ ': for I in range (5): p = multiprocessing. Process (target=process, args= (i,)) P.start ()
Note:
Multiprocessing. Process (): Creating Processes
Target: Incoming function name (method)
Args: A tuple of positional parameters passed in to a function or method
The P.start () method is used to start the process
Example 2:
Import multiprocessingimport Time def process (num): time.sleep (num) print ' process: ', num if __name__ = = ' __main __ ': For I in range (5): p = multiprocessing. Process (target=process, args= (i,)) P.start () print (' CPU number: ' + str (multiprocessing.cpu_count () )) For P in Multiprocessing.active_children (): print (' Child process name: ' + p.name + ' ID: ' + str (p.pid)) print ( ' Process Ended ')
Note:
M.cpu_count (): Gets the number of CPU cores for the current machine
M.active_children (): List of currently running process objects
Python Process Programming Express