search
HomeBackend DevelopmentPython Tutorialpython多进程操作实例

由于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
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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor