You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数执行顺序疑问:默认串行执行?是否支持并行?

Python Execution Order & Parallelism Explained

Hey there, let's break down your questions clearly and directly:

1. Default Execution Behavior: Synchronous, Sequential Execution

Absolutely! In your example:

def a(): 
    print('a')
    # Even if this contains a long-running script (like loops, file processing, etc.)
def b(): 
    print('b')

a()
b()

You can 100% guarantee that b() will only start running after a() has fully completed—no exceptions.

This is Python's default execution mode: synchronous (or sequential) execution. In this model, code runs line by line, and each statement or function call blocks the next one until it finishes. There's no automatic parallelism here; everything waits for the current task to wrap up before moving forward.

2. Ways to Achieve Parallel/Concurrent Execution

If you want a() and b() to run in parallel (or at least appear to), Python offers several tools tailored to different use cases:

Multithreading (for IO-bound tasks)

Use the threading module for tasks that spend most of their time waiting (like network requests, file reads/writes, or database queries). While Python's Global Interpreter Lock (GIL) prevents true CPU parallelism in threads, it lets you overlap waiting periods to improve efficiency.

Example:

import threading
import time

def a():
    print('a starting')
    time.sleep(2)  # Simulate an IO wait (e.g., waiting for a API response)
    print('a finished')

def b():
    print('b starting')
    time.sleep(2)
    print('b finished')

# Create and start threads
thread_a = threading.Thread(target=a)
thread_b = threading.Thread(target=b)
thread_a.start()
thread_b.start()

# Wait for both threads to finish before exiting the program
thread_a.join()
thread_b.join()

Multiprocessing (for CPU-bound tasks)

Use the multiprocessing module to bypass the GIL—each process gets its own Python interpreter and memory space, enabling true parallel execution on multi-core CPUs. This is perfect for tasks like data crunching, mathematical computations, or image processing.

Example:

import multiprocessing
import time

def a():
    print('a starting')
    time.sleep(2)
    print('a finished')

def b():
    print('b starting')
    time.sleep(2)
    print('b finished')

if __name__ == '__main__':
    process_a = multiprocessing.Process(target=a)
    process_b = multiprocessing.Process(target=b)
    process_a.start()
    process_b.start()
    process_a.join()
    process_b.join()

Asynchronous IO (for high-throughput IO-bound tasks)

Use asyncio to write concurrent code in a single thread. This relies on coroutines and an event loop to switch between tasks when they hit waiting points, making it ideal for applications like web scrapers, real-time APIs, or chat servers.

Example:

import asyncio

async def a():
    print('a starting')
    await asyncio.sleep(2)  # Async wait (doesn't block the event loop)
    print('a finished')

async def b():
    print('b starting')
    await asyncio.sleep(2)
    print('b finished')

async def main():
    # Create tasks to run concurrently
    task_a = asyncio.create_task(a())
    task_b = asyncio.create_task(b())
    await task_a
    await task_b

asyncio.run(main())

Key Terms to Look Up in Python Documentation

  • Synchronous Execution: The default model where tasks run one after another, each blocking the next.
  • Concurrent Execution: Multiple tasks making progress in overlapping time periods (can be single-threaded, like with asyncio).
  • Parallel Execution: Multiple tasks running simultaneously on separate CPU cores (like with multiprocessing).
  • Global Interpreter Lock (GIL): A mechanism in CPython that limits thread-based parallelism for CPU-bound tasks.

内容的提问来源于stack exchange,提问作者marcuse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:33:55