Python多进程/多线程通信实例
1. 多进程/多线程
多线程的定义
多线程(Multithreading) 是一种并发执行的编程技术,在一个进程内创建和管理多个线程,每个线程可以独立执行任务。线程是进程中的一个执行单元,多个线程共享进程的资源(如内存、文件句柄等),但可以独立调度和执行。
多线程的优点包括:
响应更快:在 GUI 应用程序中,可以使用一个线程处理用户输入,另一个线程执行后台任务,这样可以提高应用程序的响应速度。
资源共享:线程共享进程的资源,可以更高效地利用系统资源。
更低的开销:相比于多进程,多线程创建和上下文切换的开销较低。
多进程的定义
多进程(Multiprocessing) 是指在操作系统中同时运行多个进程,每个进程都有自己独立的内存空间和资源。进程之间通过进程间通信(IPC)进行数据交换,如管道(Pipe)、消息队列、共享内存等。
多进程的优点包括:
独立性强:每个进程都有自己独立的内存空间,不会因为一个进程的崩溃影响到其他进程的执行。
充分利用多核 CPU:多个进程可以运行在不同的 CPU 核心上,真正实现并行计算,提高计算效率。
安全性高:进程间的资源独立性提高了程序的安全性,避免了资源争用和数据竞争问题。
多线程与多进程的关系
多线程和多进程都是实现并发编程的技术手段,但它们在实现方式、适用场景和性能特性上有所不同。
实现方式:
多线程在同一个进程内创建多个线程,这些线程共享进程的内存和资源。
多进程在操作系统中创建多个进程,每个进程有自己独立的内存空间和资源。
适用场景:
多线程适用于需要共享大量数据和资源、需要快速上下文切换的场景,如 GUI 应用程序、实时系统等。
多进程适用于需要充分利用多核 CPU 进行并行计算、需要高独立性和安全性的场景,如高性能计算、分布式系统等。
性能特性:
多线程的创建和上下文切换开销较小,但需要注意线程同步和数据竞争问题。
多进程的创建和上下文切换开销较大,但进程间隔离性强,不容易出现数据竞争问题。
2. 多线程通信方式
共享变量:通过共享变量进行线程间通信,但需要使用线程同步机制(如锁)来防止数据竞争。
import threading
class SharedCounter:
def __init__(self):
self.counter = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.counter += 1
print(f"Counter: {
self.counter}")
def worker(counter: SharedCounter):
for _ in range(100):
counter.increment()
if __name__ == "__main__":
counter = SharedCounter()
threads = [threading.Thread(target=worker, args=(counter,)) for _ in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(f"Final counter value: {
counter.counter}")
事件(Event):通过设置和等待事件来进行线程间的同步和通信。
import threading
def worker(event: threading.Event):
print("Waiting for event to be set...")
event.wait()
print("Event received! Continuing work...")
if __name__ == "__main__":
event = threading.Event()
thread = threading.Thread(target=worker, args=(event,))
thread.start()
print("Main thread doing some work...")
threading.Event().wait(2) # 模拟主线程工作
print("Setting event...")
event.set()
thread.join()
队列(Queue):使用线程安全的队列(如queue.Queue)进行通信,这是最常见的方式。
import threading
import queue
def producer(queue: queue.Queue):
for i in range(5):
print(f"Producing {
i}")
queue.put(i)
threading.Event().wait(1) # 模拟生产者工作
def consumer(queue: queue.Queue):
while True:
item = queue.get()
if item is None:
break # 结束信号
print(f"Consuming {
item}")
queue<