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

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

阅读更多:Python 教程

简介

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

并发是程序内部的逻辑,它允许打开许多不同的执行路径,包括独立的I/O流、运行SQL查询等,以一种看似同时且独立的方式运行。

如何实现

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

# 步骤1-制作您今天要访问的网站URL列表
import requests

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):
"""
对网站URL进行GET请求并打印响应信息
"""
response = requests.get(site_url)
print(f' *** {site_url} 于 {response.elapsed} 秒后返回 {response.status_code}')
#让我们创建一个单独的线程来获取响应
if __name__ == '__main__':
for site_url in tutorialpoints_url:
visit_site(site_url)
print(f" *** 程序结束 ***")
*** https://www.tutorialspoint.com/python/index.htm 于 0:00:00.091103 秒后返回 200
*** https://www.tutorialspoint.com/cplusplus/index.htm 于 0:00:00.069889 秒后返回 200
*** https://www.tutorialspoint.com/java/index.htm 于 0:00:00.075864 秒后返回 200
*** https://www.tutorialspoint.com/html/index.htm 于 0:00:00.075270 秒后返回 200
*** https://www.tutorialspoint.com/cprogramming/index.htm 于 0:00:00.077984 秒后返回 200
*** 程序结束 ***

从输出中可以看出什么?网站URL是按顺序处理的,想象一下,如果有来自不同地理位置的数百个URL需要访问,那么您的程序可能会花费很多时间等待服务器响应。

现在,让我们编写一个线程化程序来并行提交请求并继续下一步而不用等待。

from threading import Thread

#请求传递的URL并返回状态码的函数
def visit_site(site_url):
"""
对网站URL进行GET请求并打印响应信息
"""
response = requests.get(site_url)
print(f' *** {site_url} 于 {response.elapsed} 秒后返回 {response.status_code}')

#循环遍历网站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 于 0:00:00.082176 秒后返回 200
*** https://www.tutorialspoint.com/html/index.htm 于 0:00:00.086269 秒后返回 200
*** https://www.tutorialspoint.com/java/index.htm 于 0:00:00.100746 秒后返回 200
*** https://www.tutorialspoint.com/cplusplus/index.htm 于 0:00:00.120744 秒后返回 200 *** https://www.tutorialspoint.com/cprogramming/index.htm 于 0:00:00.111489 秒后返回 200

讨论

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

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程