Python 自学:使用线程模块同时运行代码 Threading

news2024/11/24 9:57:28

1. 以下代码中,程序会等一个函数执行完毕才执行下一个函数。

import time

start = time.perf_counter()

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done Sleeping...')

do_something()
do_something()

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')


输出为:
Sleeping 1 second…
Done Sleeping…
Sleeping 1 second…
Done Sleeping…
Finished in 2.02 second(s)

在这里插入图片描述

2. 以下代码中,一个函数开始执行后,另一个函数也会立刻开始执行。

import time
import threading

start = time.perf_counter()

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done Sleeping...')

t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)

t1.start()
t2.start()

t1.join()
t2.join()

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')


在这里插入图片描述

3. 执行一个队列的线程

import time
import threading

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    print('Done Sleeping...')

threads = []
for _ in range(10):
    t = threading.Thread(target = do_something, args=[1.5])
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')


输出为:
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Sleeping 1.5 second(s)…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Done Sleeping…
Finished in 1.52 second(s)

4. 使用concurrent.futures库中的线程池

import time
import concurrent.futures

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return 'Done Sleeping...'

with concurrent.futures.ThreadPoolExecutor() as executor:
    f1 = executor.submit(do_something, 1)
    f2 = executor.submit(do_something, 1)

    print(f1.result())
    print(f2.result())

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')


输出为:
Sleeping 1 second(s)…
Sleeping 1 second(s)…
Done Sleeping…
Done Sleeping…
Finished in 1.02 second(s)

5. 使用map()函数执行一个数组的输入

import time
import concurrent.futures

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'

with concurrent.futures.ThreadPoolExecutor() as executor:
    secs = [5, 4, 3, 2, 1]
    results = executor.map(do_something, secs)

    for result in results:
        print(result)

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')


输出为:
Sleeping 5 second(s)…
Sleeping 4 second(s)…
Sleeping 3 second(s)…
Sleeping 2 second(s)…
Sleeping 1 second(s)…
Done Sleeping…5
Done Sleeping…4
Done Sleeping…3
Done Sleeping…2
Done Sleeping…1
Finished in 5.01 second(s)

6. 使用线程同时下载图片

先看一下不使用线程的版本:

import requests
import time

img_urls = [
    'https://images.unsplash.com/photo-1516117172878-fd2c41f4a759',
    'https://images.unsplash.com/photo-1532009324734-20a7a5813719',
    'https://images.unsplash.com/photo-1524429656589-6633a470097c',
    'https://images.unsplash.com/photo-1530224264768-7ff8c1789d79',
    'https://images.unsplash.com/photo-1564135624576-c5c88640f235',
    'https://images.unsplash.com/photo-1541698444083-023c97d3f4b6',
    'https://images.unsplash.com/photo-1522364723953-452d3431c267',
    'https://images.unsplash.com/photo-1513938709626-033611b8cc03',
    'https://images.unsplash.com/photo-1507143550189-fed454f93097',
    'https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e',
    'https://images.unsplash.com/photo-1504198453319-5ce911bafcde',
    'https://images.unsplash.com/photo-1530122037265-a5f1f91d3b99',
    'https://images.unsplash.com/photo-1516972810927-80185027ca84',
    'https://images.unsplash.com/photo-1550439062-609e1531270e',
    'https://images.unsplash.com/photo-1549692520-acc6669e2f0c'
]

time1 = time.perf_counter()

for img_url in img_urls:
    img_bytes = requests.get(img_url).content
    img_name = img_url.split('/')[3]
    img_name = f'{img_name}.jpg'

    with open(img_name, 'wb') as img_file:
        img_file.write(img_bytes)
        print(f'{img_name} was downloaded.')


time2 = time.perf_counter()

print(f'finish in {time2-time1} seconds')

输出为:
photo-1516117172878-fd2c41f4a759.jpg was downloaded.
photo-1532009324734-20a7a5813719.jpg was downloaded.
photo-1524429656589-6633a470097c.jpg was downloaded.
photo-1530224264768-7ff8c1789d79.jpg was downloaded.
photo-1564135624576-c5c88640f235.jpg was downloaded.
photo-1541698444083-023c97d3f4b6.jpg was downloaded.
photo-1522364723953-452d3431c267.jpg was downloaded.
photo-1513938709626-033611b8cc03.jpg was downloaded.
photo-1507143550189-fed454f93097.jpg was downloaded.
photo-1493976040374-85c8e12f0c0e.jpg was downloaded.
photo-1504198453319-5ce911bafcde.jpg was downloaded.
photo-1530122037265-a5f1f91d3b99.jpg was downloaded.
photo-1516972810927-80185027ca84.jpg was downloaded.
photo-1550439062-609e1531270e.jpg was downloaded.
photo-1549692520-acc6669e2f0c.jpg was downloaded.
finish in 3.0728321000933647 seconds

以下是使用线程的版本,时间缩短了1秒

import requests
import time
import concurrent.futures

img_urls = [
    'https://images.unsplash.com/photo-1516117172878-fd2c41f4a759',
    'https://images.unsplash.com/photo-1532009324734-20a7a5813719',
    'https://images.unsplash.com/photo-1524429656589-6633a470097c',
    'https://images.unsplash.com/photo-1530224264768-7ff8c1789d79',
    'https://images.unsplash.com/photo-1564135624576-c5c88640f235',
    'https://images.unsplash.com/photo-1541698444083-023c97d3f4b6',
    'https://images.unsplash.com/photo-1522364723953-452d3431c267',
    'https://images.unsplash.com/photo-1513938709626-033611b8cc03',
    'https://images.unsplash.com/photo-1507143550189-fed454f93097',
    'https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e',
    'https://images.unsplash.com/photo-1504198453319-5ce911bafcde',
    'https://images.unsplash.com/photo-1530122037265-a5f1f91d3b99',
    'https://images.unsplash.com/photo-1516972810927-80185027ca84',
    'https://images.unsplash.com/photo-1550439062-609e1531270e',
    'https://images.unsplash.com/photo-1549692520-acc6669e2f0c'
]

time1 = time.perf_counter()

def download_image(img_url):
    img_bytes = requests.get(img_url).content
    img_name = img_url.split('/')[3]
    img_name = f'{img_name}.jpg'

    with open(img_name, 'wb') as img_file:
        img_file.write(img_bytes)
        print(f'{img_name} was downloaded.')

with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.map(download_image, img_urls)

time2 = time.perf_counter()

print(f'finish in {time2-time1} seconds')

输出为:
photo-1516117172878-fd2c41f4a759.jpg was downloaded.
photo-1507143550189-fed454f93097.jpg was downloaded.
photo-1513938709626-033611b8cc03.jpg was downloaded.
photo-1516972810927-80185027ca84.jpg was downloaded.
photo-1550439062-609e1531270e.jpg was downloaded.
photo-1564135624576-c5c88640f235.jpg was downloaded.
photo-1532009324734-20a7a5813719.jpg was downloaded.
photo-1524429656589-6633a470097c.jpg was downloaded.
photo-1541698444083-023c97d3f4b6.jpg was downloaded.
photo-1530122037265-a5f1f91d3b99.jpg was downloaded.
photo-1549692520-acc6669e2f0c.jpg was downloaded.
photo-1522364723953-452d3431c267.jpg was downloaded.
photo-1493976040374-85c8e12f0c0e.jpg was downloaded.
photo-1530224264768-7ff8c1789d79.jpg was downloaded.
photo-1504198453319-5ce911bafcde.jpg was downloaded.
finish in 2.0237455000169575 seconds

线程适用于涉及IO的操作,例如上面演示的下载图片。但是,如果是涉及CPU的操作,例如处理图片,使用线程反而可能令程序执行速度下降。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/970588.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

惠普NS1005 NS1020打印机如何判断是不是该加粉了

惠普 Laser NS MFP 1005 1020系列智能闪充加粉式多功能一体机的耗材余量指示灯显示“1” “2” “2”时,就是在“说”:快没有墨粉了; 耗材余量指示灯和充粉口指示灯 在不同的状态下代表不同的意思,当耗材余量指示灯显示“1” “2”…

2023年9月上海/广州/深圳CSPM-3国标项目管理中级认证招生

CSPM-3中级项目管理专业人员评价,是中国标准化协会(全国项目管理标准化技术委员会秘书处),面向社会开展项目管理专业人员能力的等级证书。旨在构建多层次从业人员培养培训体系,建立健全人才职业能力评价和激励机制的要…

【数据结构-栈】栈基础

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:kuan 的首页,持续学…

java持久化框架JPA,自动执行sql语句的代码实现

在springboot入口处调用: import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBoot…

Mac使用VMWare安装centos7回车回退

Mac使用VMWare安装centos7回车回退 说明:本人电脑是MacBook 14pro M2芯片,安装的为VMWare16.2.5,Centos版本为centos stream9 解决方法:使用VM16.2.5Stream9Debian 11操作系统正常安装 问题:下载了VMWare16和Centos…

【微服务部署】五、Jenkins+Docker一键打包部署NodeJS(Vue)项目的Docker镜像步骤详解

NodeJS(Vue)项目也可以通过打包成Docker镜像的方式进行部署,原理是先将项目打包成静态页面,然后再将静态页面直接copy到Nginx镜像中运行。 一、服务器环境配置 前面说明了服务器Nginx的安装和配置,这里稍微有些不同&a…

java线程和go协程

一、线程的实现 线程的实现方式主要有三种:内核线程实现、用户线程实现、用户线程加轻量级进程混合实现。因为自己只对java的线程比较熟悉一点,所以主要针对java线程和go的协程之间进行一个对比。 线程模型主要有三种:1、内核级别线程&#…

微服务主流框架概览

微服务主流框架概览 目录概述需求: 设计思路实现思路分析1.HSF2.Dubbo 3.Spring Cloud5.gRPC Service mesh 参考资料和推荐阅读 Survive by day and develop by night. talk for import biz , show your perfect code,full busy,skip hardness,make a be…

深入理解作用域、作用域链和闭包

​ 🎬 岸边的风:个人主页 🔥 个人专栏 :《 VUE 》 《 javaScript 》 ⛺️ 生活的理想,就是为了理想的生活 ! ​ 目录 📚 前言 📘 1. 词法作用域 📖 1.2 示例 📖 1.3 词法作用域的…

医学专题-多组学在疾病发生发展过程中的研究思路

研究背景 单一组学数据分析通常用来解释某种特征性的生化指标与某些疾病之间的关联,但无法说明其中复杂的因果关系。从疾病表型或某种生物现象出发,寻找影响疾病发生发展的关键因子或通路,借助高通量的技术手段,设置相应的患者组…

49、IDEA 创建类或方法时,实现按格式化 ctrl + alt + l 能变成左花括号在下一行,与右花括号对齐

IDEA 创建类或方法时,左花括号是改成在下一行,与右花括号对齐 默认花括号是这样的 现在想改成这样的 实现按格式化 ctrl alt l 能变成这样 在这里修改就行 把 end of line 改成 next line

基于SSM框架金鱼销售平台源码和论文

基于SSM框架金鱼销售平台源码和论文120 开发工具:idea 数据库mysql5.7 数据库链接工具:navcat,小海豚等 技术:ssm 摘 要 随着科学技术的飞速发展,各行各业都在努力与现代先进技术接轨,通过科技手段提高自身的优…

机器人制作开源方案 | 桌面级全向底盘--本体说明+驱动控制

一、本体说明 1. 底盘概述 该底盘是一款模块化的桌面级应用型底盘,基于应用级软件架构设计、应用级硬件系统设计、典型应用型底盘机械系统设计。 底盘本体为一个采用半独立刚性悬挂的四驱全向底盘。 2. 软件环境介绍 操作系统:Ubuntu18.04系统。基于Deb…

对swap交换分区虚拟内存的理解

Swap分区的作用是什么 更新:2023-05-31 13:10 Swap是一种虚拟内存技术,在计算机内存不足时,它可以将运行中的程序或者数据存到硬盘上以释放内存空间。Swap技术不仅适用于Linux操作系统,Windows和Mac OS也有类似的技术&#xff0…

为什么各个企业都在强调要建立sop?

在现代社会中,随着科技的不断发展,各行各业的竞争也越来越激烈。为了提高工作效率,很多企业开始重视建立标准操作流程(SOP)。那么,为什么要建立SOP呢? 所谓SOP,就是 Standard Opera…

安装ArcGis时需要安装Micsoft.Net Framework 3.5 sp1

在安转ArcGis时遇到一个问题,解决方法如下 下载.Net 按照他的说明 将地址复制到迅雷中下载,并安装 就可以了 安装就可以了

MES系统在电力装备方面的应用

MES系统主要功能:解决“如何生产”的问题 通过实施MES系统,可以贯通从采购到售后服务的全制造流程,透明化生产现场运作,大大提升了生产制造各部门的管理实时性和有效性。 可获得的效益大致如下: 降低不良率&#xff…

【webrtc】接收/发送的rtp包、编解码的VCM包、CopyOnWriteBuffer

收到的rtp包RtpPacketReceived 经过RtpDepacketizer 解析后变为ParsedPayloadRtpPacketReceived 分配内存,执行memcpy拷贝:然后把 RtpPacketReceived 给到OnRtpPacket 传递:uint8_t* media_payload = media_packet.AllocatePayload(rtx_payload.size());RTC

Python break 语句

Python break语句,就像在C语言中,打破了最小封闭for或while循环。 break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。 break语句用在while和for循环中。 如果您使用嵌套循环…

关于JDK 8的HashMap

HashMap 简介 HashMap 主要用来存放键值对,它基于哈希表的 Map 接口实现,是常用的 Java 集合之一,是非线程安全的。 HashMap 可以存储 null 的 key 和 value,但 null 作为键只能有一个,null 作为值可以有多个 JDK1.8…