一文掌握Python多线程与多进程

Python的多线程和多进程

一、简介

并发是今天计算机编程中的一项重要能力,尤其是在面对需要大量计算或I/O操作的任务时。Python 提供了多种并发的处理方式,本篇文章将深入探讨其中的两种:多线程与多进程,解析其使用场景、优点、缺点,并结合代码例子深入解读。

二、多线程

Python中的线程是利用threading模块实现的。线程是在同一个进程中运行的不同任务。

2.1 线程的基本使用

在Python中创建和启动线程很简单。下面是一个简单的例子:

import threading
import time

def print_numbers():
    for i in range(10):
        time.sleep(1)
        print(i)

def print_letters():
    for letter in 'abcdefghij':
        time.sleep(1.5)
        print(letter)

thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

thread1.start()
thread2.start()

在这个例子中,print_numbersprint_letters函数都在各自的线程中执行,彼此互不干扰。

2.2 线程同步

由于线程共享内存,因此线程间的数据是可以互相访问的。但是,当多个线程同时修改数据时就会出现问题。为了解决这个问题,我们需要使用线程同步工具,如锁(Lock)和条件(Condition)等。

import threading

class BankAccount:
    def __init__(self):
        self.balance = 100  # 共享数据
        self.lock = threading.Lock()

    def deposit(self, amount):
        with self.lock:  # 使用锁进行线程同步
            balance = self.balance
            balance += amount
            self.balance = balance

    def withdraw(self, amount):
        with self.lock:  # 使用锁进行线程同步
            balance = self.balance
            balance -= amount
            self.balance = balance

account = BankAccount()

特别说明:Python的线程虽然受到全局解释器锁(GIL)的限制,但是对于IO密集型任务(如网络IO或者磁盘IO),使用多线程可以显著提高程序的执行效率。

三、多进程

Python中的进程是通过multiprocessing模块实现的。进程是操作系统中的一个执行实体,每个进程都有自己的内存空间,彼此互不影响。

3.1 进程的基本使用

在Python中创建和启动进程也是非常简单的:

from multiprocessing import Process
import os

def greet(name):
    print(f'Hello {name}, I am process {os.getpid()}')

if __name__ == '__main__':
    process = Process(target=greet, args=('Bob',))
    process.start()
    process.join()

3.2 进程间的通信

由于进程不共享内存,因此进程间通信(IPC)需要使用特定的机制,如管道(Pipe)、队列(Queue)等。

from multiprocessing import Process, Queue

def worker(q):
    q.put('Hello from

 process')

if __name__ == '__main__':
    q = Queue()
    process = Process(target=worker, args=(q,))
    process.start()
    process.join()

    print(q.get())  # Prints: Hello from process

特别说明:Python的多进程对于计算密集型任务是一个很好的选择,因为每个进程都有自己的Python解释器和内存空间,可以并行计算。

One More Thing

让我们再深入地看一下concurrent.futures模块,这是一个在Python中同时处理多线程和多进程的更高级的工具。concurrent.futures

块提供了一个高级的接口,将异步执行的任务放入到线程或者进程的池中,然后通过future对象来获取执行结果。这个模块使得处理线程和进程变得更简单。

下面是一个例子:

from concurrent.futures import ThreadPoolExecutor, as_completed

def worker(x):
    return x * x

with ThreadPoolExecutor(max_workers=4) as executor:
    futures = {executor.submit(worker, x) for x in range(10)}
    for future in as_completed(futures):
        print(future.result())

这个代码创建了一个线程池,并且向线程池提交了10个任务。然后,通过future对象获取每个任务的结果。这里的as_completed函数提供了一种处理完成的future的方式。

通过这种方式,你可以轻松地切换线程和进程,只需要将ThreadPoolExecutor更改为ProcessPoolExecutor

无论你是处理IO密集型任务还是计算密集型任务,Python的多线程和多进程都提供了很好的解决方案。理解它们的运行机制和适用场景,可以帮助你更好地设计和优化你的程序。

如有帮助,请多关注 个人微信公众号:【Python全视角】 TeahLead_KrisChang,10+年的互联网和人工智能从业经验,10年+技术和业务团队管理经验,同济软件工程本科,复旦工程管理硕士,阿里云认证云服务资深架构师,上亿营收AI产品业务负责人。

猜你喜欢

转载自blog.csdn.net/magicyangjay111/article/details/131301383