victory的博客

长安一片月,万户捣衣声

0%

python | 多线程与多进程

Python多进程与多线程

  1. Python多进程是并行执行的吗?

    答:Python多线程不是并行执行的。由于CPython解释器中有一个全局解释器锁(GIL),它会导致:

    • 同一时间内只有一个县城能执行Python字节码
    • 对于CPU密集型任务,多线程不会并行执行,线程是轮流执行的

    结论:Python在CPU密集型任务(图像处理、大量计算等)中不能并行,但在I/O密集型任务(网络请求、文件读写、数据库访问等)中非常有效,可以“并发”运行多个任务。

  2. 那么在Python中如何实现真正的并行?

    可使用multiprocessing多进程实现多个任务的并行,每个进程有自己独立的Python解释器和内存空间,不会收到GIL的限制。

  3. 多线程、多进程Python示例

    3.1 多线程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    import threading
    import time

    def worker(n):
    print(f"[Thread] Start {n}")
    time.sleep(1) # 模拟IO任务
    print(f"[Thread] Done {n} -> {n * n}")

    threads = []

    start = time.time()
    for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

    for t in threads:
    t.join()
    end = time.time()

    print(f"Threading total time: {end - start:.2f} seconds")

    3.2 多进程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    from multiprocessing import Process
    import time
    import os

    def worker(n):
    print(f"[Process {os.getpid()}] Start {n}")
    time.sleep(1) # 模拟工作
    print(f"[Process {os.getpid()}] Done {n} -> {n * n}")

    processes = []

    start = time.time()
    for i in range(5):
    p = Process(target=worker, args=(i,))
    processes.append(p)
    p.start()

    for p in processes:
    p.join()
    end = time.time()

    print(f"Multiprocessing total time: {end - start:.2f} seconds")