如何在 Python 中用线程实现并发?
pythonserver side programmingprogramming更新于 2026/2/14 22:04:17
简介
Python 有不同的方法,例如使用线程、子进程、生成器和其他技巧进行并发编程。在我们继续实现线程之前,让我们先了解一下什么是并发。
并发是单个程序中的一段逻辑,允许打开许多不同的执行路径, 包括单独的 I/O 流、运行 SQL 查询等,执行似乎既同时又相互独立。
怎么做..
首先,我们创建一个线程来遍历站点 URL,然后查看如何使用线程概念来加速程序。
# 步骤 1 - 列出您今天想要访问的网站 URL 导入请求 tutorialpoints_url = ['https://www.tutorialspoint.com/python/index.htm', 'https://www.tutorialspoint.com/cplusplus/index.htm', 'https://www.tutorialspoint.com/java/index.htm', 'https://www.tutorialspoint.com/html/index.htm', 'https://www.tutorialspoint.com/cprogramming/index.htm']
# 函数请求传递的 url 并返回状态代码
def visit_site(site_url):
"""
Makes a GET request to a website URL and prints response information
"""
response = requests.get(site_url)
print(f' *** {site_url} returned {response.status_code} after {response.elapsed} seconds')
# 让我们创建一个线程来获取响应 if __name__ == '__main__': for site_url in tutorialpoints_url: visit_site(site_url) print(f" *** end of the program ***")
*** https://www.tutorialspoint.com/python/index.htm returned 200 after 0:00:00.091103 seconds *** https://www.tutorialspoint.com/cplusplus/index.htm returned 200 after 0:00:00.069889 seconds *** https://www.tutorialspoint.com/java/index.htm returned 200 after 0:00:00.075864 seconds *** https://www.tutorialspoint.com/html/index.htm returned 200 after 0:00:00.075270 seconds *** https://www.tutorialspoint.com/cprogramming/index.htm returned 200 after 0:00:00.077984 seconds *** end of the program ***
您从输出中观察到了什么?网站 URL 是按顺序处理的,想象一下,如果您要访问来自不同地理位置的 100 个 URL,那么您的程序可能会花费大量时间等待服务器的响应。
现在让我们编写一个线程程序来并行提交请求,无需等待即可继续下一步。
from threading import Thread
# 函数请求传递的 URL 并返回状态代码
def visit_site(site_url):
"""
Makes a GET request to a website URL and prints response information
"""
response = requests.get(site_url)
print(f' *** {site_url} returned {response.status_code} after {response.elapsed} seconds')
# 循环遍历网站 url 并为每个 url 创建线程
if __name__ == '__main__':
for site_url in tutorialpoints_url:
t = Thread(target=visit_site, args=(site_url,))
t.start()
*** https://www.tutorialspoint.com/python/index.htm returned 200 after 0:00:00.082176 seconds *** https://www.tutorialspoint.com/html/index.htm returned 200 after 0:00:00.086269 seconds *** https://www.tutorialspoint.com/java/index.htm returned 200 after 0:00:00.100746 seconds *** https://www.tutorialspoint.com/cplusplus/index.htm returned 200 after 0:00:00.120744 seconds *** https://www.tutorialspoint.com/cprogramming/index.htm returned 200 after 0:00:00.111489 seconds
讨论..
线程库可用于在其自己的线程中执行任何 Python 可调用函数。
start() 方法使用 site_url 参数调用 visit_site 函数。
一旦启动,线程就会在其自己的线程中执行,该线程完全由操作系统管理。
现在,如果您想查看线程是处于活动状态还是已死亡(已完成),我们可以使用 is_alive 函数。
if t.is_alive():
print(f' *** {t} is Still executing')
else:
print(f' *** {t} is Completed')
*** <Thread(Thread-10, stopped 4820)> is Completed
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

