Python 并发编程:多线程与多进程实战
一、学习目标与重点
学习目标:掌握 Python 并发编程的基本概念和方法,包括多线程、多进程、线程池、进程池等;学习 threading、multiprocessing 等核心库的使用;通过实战案例开发并发应用程序。
学习重点:多线程的创建与管理、多进程的创建与管理、线程池与进程池、同步与互斥、并发编程实战。
二、并发编程概述
1.1 什么是并发编程
并发编程是一种编程方式,允许程序同时执行多个任务,从而提高程序的执行效率。在并发编程中,任务可以是线程或进程。
1.2 并发编程的优势
- 提高执行效率:同时执行多个任务,减少程序的总运行时间。
- 充分利用资源:充分利用 CPU 和内存资源。
- 简化代码结构:通过多线程或多进程,代码结构更加简洁。
1.3 并发编程的应用场景
- CPU 密集型任务:如数据处理、数学计算等。
- I/O 密集型任务:如文件操作、网络通信等。
三、多线程编程
2.1 线程的创建与管理
import threading
import time
# 定义线程函数
def thread_function(name):
print(f'线程 {name} 开始')
time.sleep(2)
print(f'线程 {name} 结束')
# 创建线程
thread1 = threading.Thread(target=thread_function, args=('Thread 1',))
thread2 = threading.Thread(target=thread_function, args=('Thread 2',))
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
print('所有线程结束')
2.2 线程的同步与互斥
import threading
import time
# 共享资源
counter = 0
# 互斥锁
lock = threading.Lock()
():
counter
()
lock.acquire()
:
counter +=
()
:
lock.release()
time.sleep()
()
threads = []
i ():
thread = threading.Thread(target=thread_function, args=(,))
threads.append(thread)
thread.start()
thread threads:
thread.join()
()


