关于python:一文掌握Python多线程与多进程

4次阅读

共计 2467 个字符,预计需要花费 7 分钟才能阅读完成。

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 产品业务负责人。

正文完
 0