Python Full stack Development Foundation "20th" using multiprocessing module to open process

Source: Internet
Author: User
Tags terminates

First, multiprocessing module introduction

Multithreading in Python does not take advantage of CPU resources ( primarily compute-intensive tasks ), and most of the cases in Python use multiple processes. Python provides a very good multi-process package multiprocessing.

The multiprocessing module is used to open the subprocess and perform functions (functions) in the subprocess, similar to the programming interface of the Multithreaded module threading.

multiprocessing has many functions: supporting sub-processes, communicating and sharing data, performing different forms of synchronization, providing process, Queue, Pipe, lock and other components.

Ii. Introduction to the Process class

1. Creating a class for a process

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 use a keyword to specify parameter 2. args Specifies the positional parameter to be passed to the target function, which is a tuple form and must have a comma

2. Parameter Introduction

The group parameter is not used, and the value is always nonetarget for the calling object, that is, the task that the child process is executing. Args represents the positional parameter tuple of the calling object, args= ("Egon"  ,) Kwargs represents the dictionary of the calling object, Kwargs={'name':'Egon' ,'age':}name is the name of the child process

3. Method Introduction

P.start (): Starts the process and calls the P.run () P.run () in the subprocess: The method that runs at the start of the process, is exactly what it calls the function specified by the target, and we must implement the method in the class of the custom Class  p.terminate (): Force terminates the process p, does not do any cleanup operations, if p creates a child process, the child process is a zombie process, using this method requires special care of this situation. If P also holds a lock then it will not be released, resulting in Deadlock p.is_alive (): If P is still running, return truep.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 should be emphasized that the p.join can only join the START process and not join the run-open process

4. Introduction to Properties

P.daemon: The default value is False, if set to true, which means that P is running in the background daemon, when P's parent process terminates, p also terminates, and set to True, p cannot create its own new process, must be set before P.start () P.name: Process name P.pid: Process Pidp.exitcode: The process is none at run time, if –n, indicates the end of signal N (understanding) P.authkey: The process's authentication key, which by default is a 32-character string randomly generated by os.urandom (). The purpose of this key is to provide security for the underlying interprocess communication that involves a network connection, which can only succeed if you have the same authentication key (understand it)

Third, the use of the Process class

Be sure to write the code for the open process in the If __name__== ' __main__ ': Below

To open a process and the main process is a concurrent relationship, I start to tell the operating system first I want to open a process
, and yet it won't wait, he'll go execute the following code, it's over. Once the process has started, it starts to execute

Strat (): function of the method

1. Start the process
2. Execution function

Iv. two ways to open a process

#第一种方式from multiprocessing Import Processimport timeimport randomdef Piao (name):    print ('%s is piaoing '%name)    Time.sleep (Random.randint (1,3))    print ('%s is Piao end '%name) if __name__ = = ' __main__ ':    p1 = Process (target= piao,kwargs={' name ': ' Alex '})    P2 = process (target=piao,kwargs={' name ': ' Alex '})    p3 = Process (Target=piao, kwargs={' name ': ' Alex '})    P1.start ()    P2.start ()    p3.start ()    print (' main process ')
#第二种方式from multiprocessing Import processimport timeimport randomimport osclass Piao (Process):    def __init__ (self, Name):        super (). __init__ () #必须继承父类的一些属性        self.name = name    def run (self):  #必须得实现一个run方法        Print ( Os.getppid (), Os.getpid ())        print ('%s is piaoing '%self.name)        time.sleep (Random.randint (1,3))        print ('%s Is Piao end '%self.name) if __name__ = = ' __main__ ':    p1 = Piao (' alex ') P2 = Piao (    ' Wupeiqi ')    p3 = Piao (' Yuanhao ')    P1.start ()    P2.start ()    p3.start ()    print (' main process ', Os.getpid ())

Getppid () Parent process ID
Getpid () #当前进程id

Five, multi-process implementation socket concurrency

#服务端from Socket Import *from multiprocessing Import processs = socket (af_inet,sock_stream) s.setsockopt (sol_socket,so_ reuseaddr,1) S.bind ((' 127.0.0.1 ', 8081)) S.listen (5) Print (' Start running ... ') def talk (COON,ADDR): While    True:        try:            data = COON.RECV (1024x768)            if not data:break            coon.send (Data.upper ())        except Exception:            Break    Coon.close () if __name__ = = ' __main__ ': While    True:        coon,addr = s.accept ()        print (COON,ADDR)        P =process (target=talk,args= (coon,addr))        P.start ()    s.close ()
#客户端from Socket Import *c = socket (af_inet,sock_stream) c.connect ((' 127.0.0.1 ', 8081)) while True:    cmd = input (' > (): Strip ()    if not cmd:continue    c.send (Cmd.encode (' Utf-8 '))    data = C.recv (1024x768)    print ( Data.decode (' Utf-8 ')) C.close ()

  

Python Full Stack Development Foundation "20th" using the multiprocessing module to open a process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.