在开发高并发应用时,I/O操作(如网络请求、文件读写)常常是性能瓶颈。为了提升应用的并发能力,Python中提供了多线程、多进程和异步I/O等多种技术选择。不同的场景下,选择最合适的并发模型是一个关键问题,直接影响程序的性能表现。
import threading
import requests
def fetch_url(url):
response = requests.get(url)
print(f"Fetched {url} with response code {response.status_code}")
urls = ["http://example.com", "http://example.org", "http://example.net"]
threads = []
for url in urls:
thread = threading.Thread(target=fetch_url, args=(url,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()