CPython Supported processes and threads

Source: Internet
Author: User
Tags terminates

First, multiprocessing module introduction

Multithreading in Python does not take advantage of CPU resources, 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

1 The group parameter is not used and the value is always none 2 3 target represents the calling object, which is the task to be performed by the child process 4 5 args represents the positional parameter tuple of the calling object, args= ("Egon",) 6 7 Kwargs represents the dictionary of the calling object, kwargs={' name ': ' Egon ', ' age ': 8 9 name for child process

3. Method Introduction

1 P.start (): Starts the process and calls the P.run () in the child process 2 P.run (): The method that runs at the start of a process is exactly what it calls the function specified by the target, and we must implement the method  in the class of our custom class 3 4 p.terminate (): Forcibly terminates the process p, does not make any cleanup operations, if p creates a child process, the child process is a zombie process, using this method requires special care about this situation.
If P also holds a lock then it will not be released, resulting in deadlock 5p.is_alive (): If P is still running, return true67 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,
It should be emphasized that the p.join can only join the START process and cannot 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
1  fromMultiprocessingImportProcess2 Import Time3 ImportRandom4 defPiao (name):5     Print('%s is piaoing'%name)6Time.sleep (Random.randint (1,3))7     Print('%s is Piao end'%name)8 if __name__=='__main__':9P1 = Process (target=piao,kwargs={'name':'Alex'})TenP2 = Process (target=piao,kwargs={'name':'Alex'}) OneP3 = Process (target=piao,kwargs={'name':'Alex'}) A P1.start () - P2.start () - P3.start () the     Print('Main Process')
The first way
1  fromMultiprocessingImportProcess2 Import Time3 ImportRandom4 ImportOS5 classPiao (Process):6     def __init__(self,name):7Super ().__init__()#some properties of the parent class must be inherited8Self.name =name9     defRun (self):#you have to implement a Run methodTen         Print(Os.getppid (), Os.getpid ()) One         Print('%s is piaoing'%self.name) ATime.sleep (Random.randint (1,3)) -         Print('%s is Piao end'%self.name) - if __name__=='__main__': theP1 = Piao ('Alex') -P2 = Piao ('Wupeiqi') -P3 = Piao ('Yuanhao') - P1.start () + P2.start () - P3.start () +     Print('Main Process', Os.getpid ())
The second way

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

Five, multi-process implementation socket concurrency
1  fromSocketImport*2  fromMultiprocessingImportProcess3s =socket (af_inet,sock_stream)4S.setsockopt (sol_socket,so_reuseaddr,1)5S.bind (('127.0.0.1', 8081))6S.listen (5)7 Print('Start Running ...')8 defTalk (coon,addr):9      whileTrue:Ten         Try: Onedata = COON.RECV (1024) A             if  notData Break - Coon.send (Data.upper ()) -         exceptException: the              Break - coon.close () -  - if __name__=='__main__': +      whileTrue: -COON,ADDR =s.accept () +         Print(COON,ADDR) AP =process (target=talk,args=(COON,ADDR)) at P.start () -S.close ()
Service Side
1  fromSocketImport*2c =socket (af_inet,sock_stream)3C.connect (('127.0.0.1', 8081))4  whileTrue:5cmd = input ('>>:'). Strip ()6     if  notCmd:Continue7C.send (Cmd.encode ('Utf-8'))8data = C.RECV (1024)9     Print(Data.decode ('Utf-8'))TenC.close ()
Client

CPython Supported processes and threads

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.