3 [Multi-process] - 2 ways to open multi-process

1. Multiprocessing module

(1 Introduction

Multi-threading in python cannot take advantage of multi-core. If you want to fully use the resources of multi-core CPU (os.cpu\_count\(\) view), you need to use multi-process in most cases in python.

Python provides multiprocessing.
The multiprocessing module is used to start a child process and execute our customized tasks (such as functions) in the child process. This module is similar to the programming interface of the multithreading module threading.
The multiprocessing module has many functions: supports subprocesses, communicates and shares data, performs different forms of synchronization, and provides components such as Process, Queue, Pipe, and Lock.

One point that needs to be emphasized again is that unlike threads, processes do not have any shared state, and the data modified by a process is only changed within that process.

  

(2) Code implementation

#Open process mode 1: multiprocessing

import time
from multiprocessing import Process


def task(name):
    print('%s is running' % name)
    time.sleep(2)
    print('%s is done' % name)


if __name__ == '__main__':
    p = Process(target=task, args=( ' child process 1 ' ,))
    p.start() #Just    send a signal to os, I am going to start a process

    print ( ' Main process execution ended... ' )
start process

 

 

 

 

 

2

 

3

 

4

 

5

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324537070&siteId=291194637