
并发是现代编程中的一个重要思想,它允许多个任务同时运行以提高应用程序的性能。
在 python 中实现并发的方法有多种,其中最著名的是线程和多处理。
在本文中,我们将详细探讨这两种方法,了解它们的工作原理,并讨论何时使用每种方法,以及实际的代码示例。
在我们讨论线程和多处理之前,了解并发的含义很重要。
立即学习“Python免费学习笔记(深入)”;
并发是指一个程序可以同时执行多个任务或进程。
这可以使程序更好地利用资源并运行得更快,特别是当它需要执行诸如读取文件或进行大量计算之类的操作时。
实现并发的方式主要有两种:
python 提供了两种主要方式来实现并发:
线程允许您在同一进程内运行多个较小的进程单元(称为线程),共享相同的内存空间。
线程比进程更轻,并且它们之间的切换更快。
但是,python 中的线程受全局解释器锁 (gil) 的约束,这确保一次只有一个线程可以执行 python 代码。
python的线程模块提供了一种简单灵活的方式来创建和管理线程。
让我们从一个基本示例开始:
import threading
import time
def print_numbers():
for i in range(5):
print(f"number: {i}")
time.sleep(1)
# creating a thread
thread = threading.thread(target=print_numbers)
# starting the thread
thread.start()
# wait for the thread to complete
thread.join()
print("thread has finished executing")
# output:
# number: 0
# number: 1
# number: 2
# number: 3
# number: 4
# thread has finished executing
在此示例中:
线程对于 i/o 密集型任务特别有用,例如文件操作、网络请求或数据库查询,在这些任务中程序大部分时间都在等待外部资源。
这是一个使用线程模拟下载文件的示例:
import threading
import time
def download_file(file_name):
print(f"starting download of {file_name}...")
time.sleep(2) # simulate download time
print(f"finished downloading {file_name}")
files = ["file1.zip", "file2.zip", "file3.zip"]
threads = []
# create and start threads
for file in files:
thread = threading.thread(target=download_file, args=(file,))
thread.start()
threads.append(thread)
# ensure all threads have finished
for thread in threads:
thread.join()
print("all files have been downloaded.")
# output:
# starting download of file1.zip...
# starting download of file2.zip...
# starting download of file3.zip...
# finished downloading file1.zip
# finished downloading file2.zip
# finished downloading file3.zip
# all files have been downloaded.
通过为每个文件下载创建和管理单独的线程,程序可以同时处理多个任务,从而提高整体效率。
代码中关键步骤如下:
虽然线程可以提高 i/o 密集型任务的性能,但它也有局限性:
多处理通过使用单独的进程而不是线程来解决线程的局限性。
每个进程都有自己的内存空间和python解释器,允许在多核系统上实现真正的并行。
产品介绍微趣能 Weiqn 开源免费的微信公共账号接口系统。MVC框架框架结构清晰、易维护、模块化、扩展性好,性能稳定强大核心-梦有多大核心就有多大,轻松应对各种场景!微趣能系统 以关键字应答为中心 与内容素材库 文本 如图片 语音 视频和应用各类信息整体汇集并且与第三方应用完美结合,强大的前后台管理;人性化的界面设计。开放API接口-灵活多动的API,万名开发者召集中。Weiqn 系统开发者AP
1
这使得多重处理成为需要大量计算的任务的理想选择。
python 中的多处理模块允许您轻松创建和管理进程。
让我们从一个基本示例开始:
import multiprocessing
import time
def print_numbers():
for i in range(5):
print(f"number: {i}")
time.sleep(1)
if __name__ == "__main__":
# creating a process
process = multiprocessing.process(target=print_numbers)
# starting the process
process.start()
# wait for the process to complete
process.join()
print("process has finished executing")
# output:
# number: 0
# number: 1
# number: 2
# number: 3
# number: 4
# process has finished executing
此示例与线程示例类似,但具有进程。
请注意,进程的创建和管理与线程类似,但由于进程运行在单独的内存空间中,因此它们是真正并发的,并且可以运行在不同的 cpu 核心上。
多处理对于受 cpu 限制的任务特别有用,例如数值计算或数据处理。
这是一个使用多个进程计算数字平方的示例:
import multiprocessing
def compute_square(number):
return number * number
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
# create a pool of processes
with multiprocessing.pool() as pool:
# map function to numbers using multiple processes
results = pool.map(compute_square, numbers)
print("squares:", results)
# output:
# squares: [1, 4, 9, 16, 25]
以下是代码中的关键步骤:
由于每个进程都有自己的内存空间,进程之间共享数据需要进程间通信(ipc)机制。
多处理模块提供了一些用于ipc的工具,例如queue、pipe和value。
这是一个使用队列在进程之间共享数据的示例:
import multiprocessing
def worker(queue):
# Retrieve and process data from the queue
while not queue.empty():
item = queue.get()
print(f"Processing {item}")
if __name__ == "__main__":
queue = multiprocessing.Queue()
# Add items to the queue
for i in range(10):
queue.put(i)
# Create a pool of processes to process the queue
processes = []
for _ in range(4):
process = multiprocessing.Process(target=worker, args=(queue,))
processes.append(process)
process.start()
# Wait for all processes to complete
for process in processes:
process.join()
print("All processes have finished.")
# Output:
# Processing 0
# Processing 1
# Processing 2
# Processing 3
# Processing 4
# Processing 5
# Processing 6
# Processing 7
# Processing 8
# Processing 9
# All processes have finished.
在此示例中:
虽然多处理提供了真正的并行性,但它也面临着一系列挑战:
在线程和多处理之间进行选择取决于您正在处理的任务类型:
使用线程:
使用多重处理:
python 中的并发是让应用程序运行得更快的强大方法。
线程非常适合需要大量等待的任务,例如网络操作或读/写文件,但由于全局解释器锁(gil)的原因,它对于需要大量计算的任务并不那么有效。
另一方面,多处理允许真正的并行性,使其非常适合 cpu 密集型任务,尽管它会带来更高的开销和复杂性。
无论您是处理数据、处理多个网络请求,还是进行复杂的计算,python 的线程和多重处理工具都能为您提供所需的功能,使您的程序尽可能高效、快速。
以上就是Python 中的并发性与线程和多处理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号