如何在 Python 中实现线程并发?

介绍

Python 有不同的方法,例如使用线程、子进程、生成器和其他技巧来实现并发programming.Before,我们继续并实现线程,让我们了解究竟什么是并发。

并发是单个程序中的一段逻辑,它允许打开许多不同的执行路径,包括单独的 I/O 流、运行 SQL 查询等等,执行似乎是同时的并且独立于每个其他。

怎么做..

首先我们创建一个单线程来遍历站点 url,然后看看如何使用线程概念来加速程序。

#第 1 步 - 列出您今天要访问的网站网址
import requests

tutorialpoints_url = ['https://www.nhooo.com/python/index.htm',
'https://www.nhooo.com/cplusplus/index.htm',
'https://www.nhooo.com/java/index.htm',
'https://www.nhooo.com/html/index.htm',
'https://www.nhooo.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.nhooo.com/python/index.htm returned 200 after 0:00:00.091103 seconds
*** https://www.nhooo.com/cplusplus/index.htm returned 200 after 0:00:00.069889 seconds
*** https://www.nhooo.com/java/index.htm returned 200 after 0:00:00.075864 seconds
*** https://www.nhooo.com/html/index.htm returned 200 after 0:00:00.075270 seconds
*** https://www.nhooo.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')

# Loop through the website url and create threads for each url
if __name__ == '__main__':
for site_url in tutorialpoints_url:
t = Thread(target=visit_site, args=(site_url,))
t.start()

*** https://www.nhooo.com/python/index.htm returned 200 after 0:00:00.082176 seconds
*** https://www.nhooo.com/html/index.htm returned 200 after 0:00:00.086269 seconds
*** https://www.nhooo.com/java/index.htm returned 200 after 0:00:00.100746 seconds
*** https://www.nhooo.com/cplusplus/index.htm returned 200 after 0:00:00.120744 seconds *** https://www.nhooo.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