Home Backend Development Python Tutorial python多进程操作实例

python多进程操作实例

Jun 06, 2016 am 11:20 AM
python multi-Progress

由于CPython实现中的GIL的限制,python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况我们需要使用多进程。 这也许就是python中多进程类库如此简洁好用的原因所在。在python中可以向多线程一样简单地使用多进程。

一、多进程

process的成员变量和方法:

>>class multiprocessing.Process([group[, target[, name[, args[, kwargs]]]]]) 来的定义类似于threading.Thread。target表示此进程运行的函数,args和kwargs表示target的参数。

>>name, pid

分别表示进程的名字,进程id。

>> daemon成员

daemon标志位bool变量,需要在start()调用前设置。daemon的初始值是从父进程继承而来。当一个进程结束的时候,它尝试去结束它的所有的daemon子进程。

注意:

daemon进程不允许创建子进程。否则当daemon进程结束的时候它的子进程不能被结束。

这里的daemon不是Unix的daemon进程,当父进程结束的时候所有的daemon子进程也将被终止(对于非daemon进程,父进程不等待非daemon的紫子进程,除非显示地对非daemon子进程使用join()方法)。

>>  exitcode

如果进程还没有退出,则为None,如果正确的退出则为0,如果有错误则为>0的错误代码,如果进程为终止则为-1*singal。 

>> start(), is_live(), terminate()

start()用来启动进程,is_live()用来查看进程的状态,terminate()用来终止进程。

>> run()

可以在process的子类中重载run()方法,从而设定进程的任务。重载process是构造新进程的另一种方式,一定程度上上等价于process的target参数。

multiprcessing的静态方法:

>>  multiprocessing.cpu_count()

用来获得当前的CPU的核数,可以用来设置接下来子进程的个数。

>>  multiprocessing.active_children()

用来获得当前所有的子进程,包括daemon和非daemon子进程。

实例:

代码如下:


import multiprocessing
import time
import sys

def worker(num):
    p = multiprocessing.current_process()
    print ('Starting:' + p.name + ":" + str(p.pid))
    print(str(num))
    sys.stdout.flush()
    print ('Exiting :' + p.name + ":" + str(p.pid))
    sys.stdout.flush()

def daemon():
    p = multiprocessing.current_process()
    print ('Starting:' + p.name + ":" + str(p.pid))
    sys.stdout.flush()
    time.sleep(10)
    print ('Exiting :' + p.name + ":" + str(p.pid))
    sys.stdout.flush()
   
def non_daemon():
    p = multiprocessing.current_process()
    print ('Starting:' + p.name + ":" + str(p.pid))
    sys.stdout.flush()
    time.sleep(20)
    print ('Exiting :' + p.name + ":" + str(p.pid))
    sys.stdout.flush()
   
if __name__ == '__main__':
    w = multiprocessing.Process(name='worker', target=worker, args=(100,))
    d = multiprocessing.Process(name='daemon', target=daemon)
    d.daemon = True
    nd = multiprocessing.Process(name='non-daemon', target=non_daemon)
    w.start()
    d.start()
    nd.start()
   
    print("the number of CPU is " + str(multiprocessing.cpu_count()))
    print("All children processes:")
    for p in multiprocessing.active_children():
        print("child:" + p.name + ":" + str(p.pid))
    print()
   
    w.join()
    #d.join()

运行结果:

可以从上面的例子看到没有多非daemon子进程使用join()方法,结果父进程没有等待非daemon进程结束就退出了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles