当前位置: 首页 > article >正文

Python线程使用

使用 time.sleep 来模拟 I/O 密集型任务(如爬取数据),并展示如何通过线程实现这些任务的并发执行。为了更清楚地体现出线程可以同步进行多个任务,将打印出每个任务的状态和时间戳。 

import threading
import time


# 模拟从网站获取数据的任务
def fetch_website(url, delay):
    print(f"{time.ctime()} - Fetching {url}...")
    time.sleep(delay)  # 模拟网络请求的延迟
    print(f"{time.ctime()} - Fetched {url}")


# 使用线程并发获取多个网站的数据
def fetch_websites(urls, delays):
    threads = []

    for url, delay in zip(urls, delays):
        thread = threading.Thread(target=fetch_website, args=(url, delay))
        print(f"{time.ctime()} - Starting thread for {url}...")
        threads.append(thread)
        print(f"{time.ctime()} - Thread {thread.name} started.")
        thread.start()
        print(f"{time.ctime()} - Thread {thread.name} started.")

    # 等待所有线程完成
    for thread in threads:
        print("Waiting for all threads...")
        thread.join(15)
        print(f"{time.ctime()} - Thread {thread.name} completed.")


if __name__ == "__main__":
    start_time = time.time()

    urls = [
        "https://www.example.com",
        "https://www.python.org",
        "https://www.github.com",
        "https://www.wikipedia.org"
    ]

    delays = [5, 20, 3, 10]  # 每个任务的不同延迟时间

    print(f"{time.ctime()} - Starting to fetch websites...")
    fetch_websites(urls, delays)
    end_time = time.time()

    print(f"{time.ctime()} - All websites fetched.")
    print(f"Total time taken: {end_time - start_time:.2f} seconds")

Sun Dec  1 12:40:59 2024 - Starting to fetch websites...
Sun Dec  1 12:40:59 2024 - Starting thread for https://www.example.com...
Sun Dec  1 12:40:59 2024 - Thread Thread-1 (fetch_website) started.
Sun Dec  1 12:40:59 2024 - Fetching https://www.example.com...Sun Dec  1 12:40:59 2024 - Thread Thread-1 (fetch_website) started.

Sun Dec  1 12:40:59 2024 - Starting thread for https://www.python.org...
Sun Dec  1 12:40:59 2024 - Thread Thread-2 (fetch_website) started.
Sun Dec  1 12:40:59 2024 - Fetching https://www.python.org...Sun Dec  1 12:40:59 2024 - Thread Thread-2 (fetch_website) started.

Sun Dec  1 12:40:59 2024 - Starting thread for https://www.github.com...
Sun Dec  1 12:40:59 2024 - Thread Thread-3 (fetch_website) started.
Sun Dec  1 12:40:59 2024 - Fetching https://www.github.com...Sun Dec  1 12:40:59 2024 - Thread Thread-3 (fetch_website) started.

Sun Dec  1 12:40:59 2024 - Starting thread for https://www.wikipedia.org...
Sun Dec  1 12:40:59 2024 - Thread Thread-4 (fetch_website) started.
Sun Dec  1 12:40:59 2024 - Fetching https://www.wikipedia.org...Sun Dec  1 12:40:59 2024 - Thread Thread-4 (fetch_website) started.

Waiting for all threads...
Sun Dec  1 12:41:02 2024 - Fetched https://www.github.com
Sun Dec  1 12:41:04 2024 - Fetched https://www.example.com
Sun Dec  1 12:41:04 2024 - Thread Thread-1 (fetch_website) completed.
Waiting for all threads...
Sun Dec  1 12:41:09 2024 - Fetched https://www.wikipedia.org
Sun Dec  1 12:41:19 2024 - Fetched https://www.python.org
Sun Dec  1 12:41:19 2024 - Thread Thread-2 (fetch_website) completed.
Waiting for all threads...
Sun Dec  1 12:41:19 2024 - Thread Thread-3 (fetch_website) completed.
Waiting for all threads...
Sun Dec  1 12:41:19 2024 - Thread Thread-4 (fetch_website) completed.
Sun Dec  1 12:41:19 2024 - All websites fetched.
Total time taken: 20.00 seconds

进程已结束,退出代码为 0

 


http://www.kler.cn/a/420777.html

相关文章:

  • brew安装mongodb和php-mongodb扩展新手教程
  • Algorithm:河内之塔
  • linux 获取公网流量 tcpdump + python + C++
  • MAUI APP开发蓝牙协议的经验分享:与跳绳设备对接
  • 为什么编程语言会设计不可变的对象?字符串不可变?NSString *s = @“hello“变量s是不可变的吗?Rust内部可变性的意义?
  • window 下用Ollama 开发一个简单文档问答系统
  • linux arm下获取屏幕事件(rk3588)
  • 大模型开发和微调工具Llama-Factory-->训练方法(SFT, RLHF, DPO, KTO)
  • Android 编译和使用libheif
  • playwright 学习复仇记-2 Selector选择器定位元素
  • vmware虚拟机移植
  • 多线程 03 实现方式
  • 三维开发中blender建模后如何完美兼容到threejs
  • SAP HANA 上进行 ABAP 开发:简介
  • 设计模式 更新ing
  • 简单快速的上手python
  • node.js基础学习-zlib模块-压缩解压(八)
  • 护航开源大赛,赋能数字未来
  • Milvus python库 pymilvus 常用操作详解之Collection(上)
  • 算力100问☞第32问:密集计算的关键技术有哪些?
  • Pytest --capture 参数详解:如何控制测试执行过程中的输出行为
  • 【ONE·基础算法 || 动态规划(三)】
  • 基于Java Springboot成人教育APP且微信小程序
  • Web实时通信@microsoft/signalr
  • C语言第十四周课——课堂练习
  • pip更换国内源,加速Python包下载(附2024年12月最新国内镜像源列表)