Python编程:multiprocessing多进程

简介: Python编程:multiprocessing多进程

获取进程id

import multiprocessing
import os
def foo():
    print(__name__)
    print("parent:", os.getppid())
    print("current:", os.getpid())
if __name__ == "__main__":
    foo()  # 主进程调用
    p = multiprocessing.Process(target=foo)
    p.start()  # 新开进程调用
    """
    __main__
    parent: 952
    current: 188
    __mp_main__
    parent: 188
    current: 6492
    """

多进程测试

import multiprocessing
import time, threading
from pycharm_fontcolor import Colors, FontColor
def func(i):
    print(FontColor.set_color("线程号:{}".format(threading.get_ident()), Colors.green), i)
def foo(i):
    print(FontColor.set_color("进程:", Colors.red), i)
    t = threading.Thread(target=func, args=(i,))  # 进程中新开线程
    t.start()
if __name__ == "__main__":
    start_time = time.time()
    for i in range(5):
        p = multiprocessing.Process(target=foo, args=(i,))
        p.start()
    end_time = time.time()
    print(FontColor.set_color("时间:", Colors.blue), end_time - start_time)
    """
    时间: 0.05303597450256348
    进程: 0
    线程号:8968 0
    进程: 1
    线程号:7620 1
    进程: 2
    进程: 3
    线程号:9204 2
    线程号:2492 3
    进程: 4
    线程号:6512 4
    """

备注:

pycharm_fontcolor是自己写的模块,可以参考文章:

Python编程:pycharm控制台字体颜色


进程池


from multiprocessing import  Pool
import time, os
def foo(i):
    time.sleep(2)
    print("process:", i, os.getpid())
    return i + 1  # 参数将传递给回调函数
def bar(i): # 做回调函数,由主进程执行
    print("bar", i, os.getpid())
if __name__ == "__main__":
    print(os.getpid())
    pool = Pool(processes=3)  # 允许同时放入3个进程
    for i in range(10):
        # p = pool.apply(func=foo, args=(i,))  # 串行
        p = pool.apply_async(func=foo, args=(i,), callback=bar)  # 并行
    print("done")
    pool.close()  # 先关闭入口
    pool.join()  # 在等待执行
    """
    8120
    done
    process: 0 5452
    bar 1 8120
    process: 1 8360
    bar 2 8120
    process: 2 7908
    bar 3 8120
    process: 3 5452
    bar 4 8120
    process: 4 8360
    bar 5 8120
    process: 5 7908
    bar 6 8120
    process: 6 5452
    bar 7 8120
    process: 7 8360
    bar 8 8120
    process: 8 7908
    bar 9 8120
    process: 9 5452
    bar 10 8120
    """

进程队列

from multiprocessing import Process, Queue
def foo(q):
    q.put("你好")
if __name__ == "__main__":
    q = Queue()  # 进程队列
    p = Process(target=foo, args=(q,))
    # p = Thread(target=foo, args=(q,))
    p.start()
    print(q.get())  # 你好

进程管道

from multiprocessing import Process, Pipe
def foo(conn):
    conn.send("hello")
    conn.close()
if __name__ == "__main__":
    parent_conn, child_conn = Pipe()  # 管道传送数据
    p = Process(target=foo, args=(child_conn,))
    p.start()
    print(parent_conn.recv())  # hello

多进程实现数据共享

from multiprocessing import Process, Manager
import os
def foo(dct, lst):
    dct[os.getpid()] = os.getpid()
    lst.append(os.getpid())
    print(os.getpid())
if __name__ == "__main__":
    manager = Manager()  # 实现进程间共享数据
    dct = manager.dict()
    lst = manager.list()
    processes = []
    for i in range(5):
        p = Process(target=foo, args=(dct, lst))
        p.start()
        processes.append(p)
    for process in processes:  # 等待结果
        process.join()
    print(dct)
    print(lst)
    """
    3816 5376 7500 8332 1124
    {3816: 3816, 5376: 5376, 8332: 8332, 7500: 7500, 1124: 1124}
    [3816, 5376, 7500, 8332, 1124]
    """

进程锁

from multiprocessing import Lock, Process
def foo(lock, i):
    lock.acquire()
    print("hello world!", i)
    lock.release()
if __name__ == "__main__":  # 主动执行会继续下面的内容,被当做模块调用则不会
    lock = Lock()  # 实例化进程锁
    for i in range(5):
        p = Process(target=foo, args=(lock, i))
        p.start()
    """
    hello world! 2
    hello world! 1
    hello world! 0
    hello world! 3
    hello world! 4
    """

相关文章
|
3月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
319 102
|
2月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
219 3
|
2月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
483 3
|
2月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
300 3
|
2月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
312 0
|
数据采集 并行计算 安全
Python并发编程:多进程(multiprocessing模块)
在处理CPU密集型任务时,Python的全局解释器锁(GIL)可能会成为瓶颈。为了充分利用多核CPU的性能,可以使用Python的multiprocessing模块来实现多进程编程。与多线程不同,多进程可以绕过GIL,使得每个进程在自己的独立内存空间中运行,从而实现真正的并行计算。
|
Unix Linux API
Python multiprocessing模块
Python multiprocessing模块
在Python中,`multiprocessing`模块提供了一种在多个进程之间共享数据和同步的机制。
在Python中,`multiprocessing`模块提供了一种在多个进程之间共享数据和同步的机制。
|
数据采集 Java Python
python并发编程:使用多进程multiprocessing模块加速程序的运行
python并发编程:使用多进程multiprocessing模块加速程序的运行
425 1
|
安全 Python Windows
Python 的并发编程:在 Python 中如何使用 `threading` 和 `multiprocessing` 模块?
Python 的并发编程:在 Python 中如何使用 `threading` 和 `multiprocessing` 模块?
175 1

推荐镜像

更多