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


简介

Python 有不同的方法,例如使用线程、子进程、生成器和其他技巧来进行并发编程。在我们继续实现线程之前,让我们先了解一下并发到底是什么。

并发是指在一个程序内部允许打开许多不同的执行路径,包括独立的 I/O 流、运行 SQL 查询等,使得执行看起来既是同时发生的又是相互独立的。

如何操作..

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

# Step 1 - Make a list of website url you want to visit today
import requests

tutorialpoints_url = ['https://tutorialspoint.com/python/index.htm',
'https://tutorialspoint.com/cplusplus/index.htm',
'https://tutorialspoint.com/java/index.htm',
'https://tutorialspoint.com/html/index.htm',
'https://tutorialspoint.com/cprogramming/index.htm']


# function to request the url passed and return the status code
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')


# Let us create a single thread to fetch the response
if __name__ == '__main__':
for site_url in tutorialpoints_url:
visit_site(site_url)
print(f" *** end of the program ***")


*** https://tutorialspoint.com/python/index.htm returned 200 after 0:00:00.091103 seconds
*** https://tutorialspoint.com/cplusplus/index.htm returned 200 after 0:00:00.069889 seconds
*** https://tutorialspoint.com/java/index.htm returned 200 after 0:00:00.075864 seconds
*** https://tutorialspoint.com/html/index.htm returned 200 after 0:00:00.075270 seconds
*** https://tutorialspoint.com/cprogramming/index.htm returned 200 after 0:00:00.077984 seconds
*** end of the program ***

你从输出中观察到了什么?站点 URL 是按顺序处理的,想象一下,如果你有来自不同地理位置的数百个 URL 要访问,那么你的程序可能会花费大量时间等待服务器响应。

现在让我们编写一个线程程序,以并行方式提交请求,并在不等待的情况下继续执行下一步。

from threading import Thread

# function to request the url passed and return the status code
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://tutorialspoint.com/python/index.htm returned 200 after 0:00:00.082176 seconds
*** https://tutorialspoint.com/html/index.htm returned 200 after 0:00:00.086269 seconds
*** https://tutorialspoint.com/java/index.htm returned 200 after 0:00:00.100746 seconds
*** https://tutorialspoint.com/cplusplus/index.htm returned 200 after 0:00:00.120744 seconds *** https://tutorialspoint.com/cprogramming/index.htm returned 200 after 0:00:00.111489 seconds

讨论..

  • threading 库可用于在自己的线程中执行任何 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

更新于: 2020-11-09

209 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.