多线程和多进程是Python中处理并发的重要概念。以下是一些基本概念和技巧。

多线程

多线程允许在同一程序中同时运行多个线程,这可以用于执行I/O密集型或CPU密集型任务。

创建线程

使用threading模块可以轻松创建线程。

import threading

def print_numbers():
    for i in range(10):
        print(i)

# 创建线程
t = threading.Thread(target=print_numbers)

# 启动线程
t.start()

# 等待线程完成
t.join()

线程同步

当多个线程访问共享资源时,可能需要同步以避免数据竞争。

import threading

# 创建一个锁对象
lock = threading.Lock()

def print_numbers():
    for i in range(10):
        lock.acquire()
        try:
            print(i)
        finally:
            lock.release()

# 创建线程
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)

# 启动线程
t1.start()
t2.start()

# 等待线程完成
t1.join()
t2.join()

多进程

多进程是另一种处理并发的技术,它为每个进程提供独立的内存空间。

创建进程

使用multiprocessing模块可以创建进程。

from multiprocessing import Process

def print_numbers():
    for i in range(10):
        print(i)

# 创建进程
p = Process(target=print_numbers)

# 启动进程
p.start()

# 等待进程完成
p.join()

进程通信

进程间可以通过多种方式通信,如共享内存、管道、队列等。

from multiprocessing import Process, Queue

def producer(queue):
    for i in range(10):
        queue.put(i)
        print(f"Produced: {i}")

def consumer(queue):
    while True:
        i = queue.get()
        if i is None:
            break
        print(f"Consumed: {i}")

# 创建进程和队列
producer_process = Process(target=producer, args=(Queue(),))
consumer_process = Process(target=consumer, args=(Queue(),))

# 启动进程
producer_process.start()
consumer_process.start()

# 等待进程完成
producer_process.join()
consumer_process.join()

更多信息,请参考 Python 多进程教程

返回课程中心