在 Python 中,理解并发(Concurrency)、并行(Parallelism)、同步(Synchronization)、异步(Asynchronous)、阻塞(Blocking)和非阻塞(Non-blocking)是非常重要的,因为它们是构建高性能应用程序的关键概念。
1. 并发(Concurrency)
并发是指程序在同一时间段内可以处理多个任务的能力。具体来说,程序看起来像是同时执行多个任务,但实际上它们是在交替执行。
1.1 示例:多线程
import threading
import time
def worker():
print(f"Thread {threading.current_thread().name} started")
time.sleep(2)
print(f"Thread {threading.current_thread().name} finished")
# 创建多个线程
threads = []
for i in range(5):
thread = threading.Thread(target=worker, name=f"Thread-{i}")
threads.append(thread)
thread.start()
#